我创建了一个自定义函数,该函数需要在服务器的每条路由中执行。
此函数需要在请求的标头中检索参数,并在数据库内部检查此参数。 (由存储库控制)
如何在我的函数中访问该存储库?
我尝试了不同的可能性,但我无法获得结果:
我是回送和打字稿的初学者,如您所见=)
答案 0 :(得分:0)
我认为您正在寻找最近推出的拦截器,请参见Interceptors和Interceptor generator。
由于要为每个传入请求调用函数,因此可以使用全局拦截器。
如何在我的函数中访问该存储库?
编写一个拦截器提供程序,它使您可以利用基于@inject
的依赖项注入来接收存储库。例如:
class MyRequestValidator implements Provider<Interceptor> {
constructor(
@repository(TokenRepository) protected tokenRepo: TokenRepository,
@inject(RestBindings.Http.REQUEST) protected request: Request,
) {}
value() {
return this.intercept.bind(this);
}
async intercept<T>(
invocationCtx: InvocationContext,
next: () => ValueOrPromise<T>,
) {
// parse the parameter from this.request.headers[name]
const token = this.request.headers['x-my-token'];
// call this.tokenRepo methods to query the database
const found = await this.tokenRepo.findOne({where:{id: token}});
const isValid = !found.expired;
if (!isValid) {
// throw new Error() to abort with error
throw new HttpErrors.BadRequest('Invalid token.'));
}
// call next() to continue with request handling
return next();
}
}