参数装饰器修饰函数参数,一般应用场景配合方法装饰器一起,达到检查参数的目的。
参数装饰器表达式会在运行时当作函数被调用,传入下列3个参数:
下面通过例子具体查看。
根绝参数器找到返回的值,然后利用方法装饰器返回处理后的结果。
import "reflect-metadata";
const response: ParameterDecorator = (
target: Object,
propertyKey: string | symbol,
parameterIndex: number
) => {
Reflect.defineMetadata("response", parameterIndex, target, propertyKey);
};
const get: (path: string) => MethodDecorator = (path) => {
return (
target: Object,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => {
let originMethod = descriptor.value;
let index = Reflect.getMetadata("response", target,propertyKey);
descriptor.value = function () {
arguments[index] = {'data':'返回值'}
let arr = []
for (const eindex in arguments) {
if (Object.prototype.hasOwnProperty.call(arguments, eindex)) {
const element = arguments[eindex];
arr.push(element)
}
}
originMethod(...arr)
};
};
};
class HttpReq {
@get("/getAllData")
getAllData(request: {}, @response res?:{}) {
console.log(res);
}
}
let http = new HttpReq()
http.getAllData({'data':'requestBody'})