如何在 loopback4 中创建自定义装饰器?

问题描述

  async checkUserMemberOfProduct(userId: string,productId: string) {
    if (userId && productId) {
       const user = await Product.find({ where: { userId: userId,id: productId } });
       return !!user;
    }
    return false;
  }

我想创建这个函数作为装饰器。并在端点上方调用它。例如

  @checkUserMemberOfProduct()

  @post('/roles')
  async create(
    @requestBody() user: User
  ): Promise<Role> {
    return this.roleRepository.create(role);
  }

但我不确定如何将请求正文传递给这个装饰器。可以用这个 fn 作为装饰器吗?

解决方法

我认为拦截器可以工作。这是示例代码。

import {inject,intercept,Interceptor} from '@loopback/context';
import {get,HttpErrors,RestBindings} from '@loopback/rest';

const myInterceptor: Interceptor = async (invocationCtx,next) => {
  // your code 
  // goes here

  // if success
  next()

  // if error
  throw new HttpErrors.NotFound();
};

export class PingController {
  constructor() {}

  @intercept(myInterceptor)
  @post('/test')
  async test(@requestBody() body: any) {
    // some code
  }
}