装饰器效果非预期
来源:14-1 Koa2 课程回顾总结

Seadog16
2018-12-01
老师,你全程就是敲代码,一点解释都没有,看得好累。
我现在仿造你得登录,写了如下代码。遇到问题了:
- 问题:参照你的方法写的装饰器,返回错误码,但是在login方法里面还是会被下面的body覆盖了接口返回。如果是这样的话,装饰器的作用就失效了。
- 期望:如果在装饰器里判断缺少必填属性,直接返回错误码,而不去执行方法里的接口返回。
请教老师如何做。
// decorator.ts
import _ from 'lodash';
const decorator = (middleware: any) =>
(target: any, key: string, descriptor: any) => {
const method = descriptor.value;
descriptor.value = (ctx: any, next: any) => {
middleware(ctx, next);
return method.apply(target, [ctx, next]);
};
return descriptor;
};
interface IRule {
body?: string[];
query?: string[];
[propName: string]: any;
}
export const Required = (rules: IRule) => decorator(async (ctx: any, next: any) => {
const request = ctx.request;
let err: string[] = [];
_.forEach(rules, (value: any, key) => {
if (value) err = value.filter((v: any) => !_.has(request[key], v));
});
if (err.length) {
ctx.body = {
code: 412,
msg: `${err.join(',')} is required`
};
}
await next();
});
// member.ts
import { Required } from '../lib/decorator';
class Member {
@Required({
body: ['user', 'pass']
})
static async login (ctx: any, next: any) {
console.log(ctx.body);
return (ctx.body = {
msg: '123',
code: 1234
});
}
}
export default Member;
写回答
1回答
-
把这个改成
if (err.length) {
return (ctx.body = {
code: 412,
msg: `${err.join(',')} is required`
});
} else {await next()
}
这样处理试试呢?
122018-12-03
相似问题