0
我使用koa
和Typescript
實現許多的API,但在一些API,我需要檢查,如果用戶登錄,我這樣做:如何驗證登錄前的操作?
export async function list_products(req: product.list_normal.Request):promise<product.list_normal.Response> {
// no need to check login here
....
return products;
}
export async function pay(req: shop.pay.Request): promise<shop.pay.Response> {
const isLogin = this.session && this.session.userInfo && this.session.userInfo.userId;
// check login here
if (!isLogin) {
return {
errorId: "need_login.error",
errorDesc: "please login"
}
}
...
return resp
}
的問題是,我需要各做時間,我想是這樣的:
function need_login(target: Object, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) {
let originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
const req = args[0]
if (!req.factoryUserId) {
return {
errorId: "need_login_error",
errorDesc: "please login",
}
} else {
let result = originalMethod.apply(this, args); // run and store the result
return result; // return the result of the original method
}
};
return descriptor;
}
export async function list_products(req) {
....
return products;
}
@need_login
export async function pay(req) {
...
return resp
}
,你可以看到,我在pay
方法中添加一個裝飾need_login
,這應該是很大的,但是Typescript
裝飾不能在函數中使用:
Decorators are not valid here
所以我問我有什麼選擇做這個簡單的?