依次使用存储库的自定义功能

时间:2019-06-07 08:20:35

标签: typescript repository loopbackjs

我创建了一个自定义函数,该函数需要在服务器的每条路由中执行。

此函数需要在请求的标头中检索参数,并在数据库内部检查此参数。 (由存储库控制)

如何在我的函数中访问该存储库?

我尝试了不同的可能性,但我无法获得结果:

  1. 在函数内部创建一个存储库(数据库似乎为空:()
  2. 尝试从控制器传递存储库(可以,但是在顺序文件中,我无法访问控制器或存储库:(
  3. 尝试将控制器包含在函数中,但类似于2。

我是回送和打字稿的初学者,如您所见=)

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找最近推出的拦截器,请参见InterceptorsInterceptor 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();
  }
}