我尝试通过创建实例
来停止执行某个功能基本示例
class Foo {
constructor(continueExec) {
return continueExec;
}
}
(() => {
const guard = new Foo(false);
console.log('hello');
})()
我的使用案例
我正在将Express.js与Typescript一起使用,并希望top创建一个Guard类,以便在服务器路由中单独使用
声明
class Guard {
user;
res;
constructor(req?: any, res?:any) {
this.res = res;
try {
this.user = Guard.jwt.verify(req.get('Authorization'), Guard.secret); // All requests, where the user hast to be logged in are send with a JWT in the header
} catch(err) {
this.deny(err.message); // Validation of JWT failed, so the request must be aborted;
}
}
isManager () {
if (!this.user.roles.includes("manager"))
this.deny("You aren't a Manager");
}
deny(err:string = 'Access Denied') {
this.res.json({
success: false,
err: err
});
return false;
}
}
应用
router.get('/deleteCourse/:id', (req, res) => {
new Guard(req,res).isManager(); //Stop execution if token is invalid or user is not a manager
// Course will be deleted and terminate with
res.json({success: true}
})
我知道我可以使用if语句,但我想避免这种情况,以尽可能保持脚本清洁。
我的方法是否可行,或者您能提供更好的方法吗?
使用一个if语句的可能解决方案
router.get('/deleteCourse/:id', (req, res) => {
const guard = new Guard(req,res);
if (guard.user && guard.isManager() {
//Continue Execution
}
})