如何解决如何在运行时将参数传递给TypeScript装饰器?
我想在运行时将参数传递给TypeScript装饰器,以便装饰的方法将使用该参数,原始方法不会要求此函数起作用,但装饰器会使用它。
我试图通过将一个参数传递给装饰的方法,然后在原始方法的参数中的装饰器中找到它来实现这一点。
例如我尝试过的事情:
// calling a decorated method (nestJS code)
@Get('')
@UseGuards(JwtAuthGuard)
async getAll(@CurrentUser() user: User): Promise<any[]> {
//current user is a nestJS decorator extracts the user from the http header
const res = await this.whateverService.original(user);
return res;
}
// @MyDecorator usage
@MyDecorator()
async original(@user user: User): Promise<any>{
// return get all whatever
}
// @MyDecorator decorator
export function MyDecorator() {
return function (target: Object,propertyName: string | symbol,descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
// get user param index
const userParamIndex = Reflect.getOwnMetadata(
userMetadataKey,target,propertyName
);
if (userParamIndex === undefined) {
throw new Error(`user undefined or missing @user decorator in method ${propertyName.toString()}`);
}
// override method descriptor with proxy method
descriptor.value = async function (...args: any[]) {
return new Promise(async (resolve,reject) => {
const user = args[userParamIndex];
let res;
try {
// await stuff using user arg;
res = await originalMethod();
} catch (err) {
reject(err);
} finally {
// await stuff;
resolve(res);
}
});
};
};
}
// @user decorator
export function user(
target: Object,propertyKey: string | symbol,parameterIndex: number
): void {
Reflect.defineMetadata(
userMetadataKey,parameterIndex,propertyKey
);
}
此实现的问题是原始的user
参数在IDE中被标记为declared but its value is never read.
。
是否可以让IDE知道装饰器中正在使用它? 也许为此更好的实现?
编辑
对于更多上下文,我添加的代码已简化,并且不包含所有功能。 这样做的目的是:
- 从连接池获得到postgres db的单个连接。
- 出于行级安全需要,将current_user_id设置为会话运行时变量。
- 执行将执行数据库查询的原始方法。
- 重置会话运行时变量。
- 释放连接
- 返回原始方法的结果。
技术堆栈:NestJS和TypeORM。 我正在尝试模仿TypeORM's Transaction decorator之类的东西,但具有更多功能。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。