按顺序使用存储库的自定义函数
Custom function using repository in sequence
我创建了一个需要在服务器的每个路由中执行的自定义函数。
这个函数需要在请求头中获取一个参数,并在数据库中检查这个参数。 (由存储库控制)
如何在我的函数中获得此存储库的访问权限?
我尝试了不同的可能性,但我无法获得结果:
- 在函数内创建一个存储库(数据库似乎是空的 :( )
- 尝试从控制器传递存储库(没问题,但在序列文件中我无法访问控制器或存储库:(
- 尝试在函数中包含控制器,但喜欢 2。
如您所见,我是 loopback 和 typescript 的初学者 =)
我认为您正在寻找最近推出的拦截器,请参阅 Interceptors and Interceptor generator。
由于您想为每个传入请求调用您的函数,您可以使用全局拦截器。
how can I gain the access of this repository within my function?
编写拦截器提供程序,它允许您利用基于 @inject
的 dependency-injection 来接收存储库。例如:
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();
}
}
我创建了一个需要在服务器的每个路由中执行的自定义函数。
这个函数需要在请求头中获取一个参数,并在数据库中检查这个参数。 (由存储库控制)
如何在我的函数中获得此存储库的访问权限?
我尝试了不同的可能性,但我无法获得结果:
- 在函数内创建一个存储库(数据库似乎是空的 :( )
- 尝试从控制器传递存储库(没问题,但在序列文件中我无法访问控制器或存储库:(
- 尝试在函数中包含控制器,但喜欢 2。
如您所见,我是 loopback 和 typescript 的初学者 =)
我认为您正在寻找最近推出的拦截器,请参阅 Interceptors and Interceptor generator。
由于您想为每个传入请求调用您的函数,您可以使用全局拦截器。
how can I gain the access of this repository within my function?
编写拦截器提供程序,它允许您利用基于 @inject
的 dependency-injection 来接收存储库。例如:
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();
}
}