将管道用于 NestJs 中的服务功能

UsePipes for a service function in NestJs

是否可以将验证管道用于服务功能?我想在 class 中创建对象的函数中检查我的数据,但它似乎没有效果:

@UsePipes(new ValidationPipe())
async create(createMemberDto: CreateMemberDto, temp: boolean=false) {
    // Do something
}

对于我在控制器中的端点,该管道运行良好,但对于服务中的此功能则不然(如果缺少值,则不会抛出异常)。

我该如何处理,或者有什么替代方法吗?

不,这是不可能的。 @UsePipes() 设置 Nest 稍后读取的元数据。当 Nest 启动时,它基本上将每个路由设置为底层 HTTP 适配器的中间件。在这个中间件中,Nest 检查所有可能的元数据(方法类型、路由名称、使用管道、使用守卫、使用拦截器和使用过滤器),然后检查路由处理程序参数的元数据(req、body、param、query 等) ) 并且基本上做了这样的事情(大量的伪代码进来,实际代码更清晰,写得更好)

const foundClasses = await this.discoveryService.findClassesWithMetadata(ControllerMetadata);
for (const found of foundClasses) {
  const routes = await this.discoveryService.findMethodsOfClassWithMetadata(RouteHandlerMetadata, found);
  for (const route of routes) {
    const usePipes = this.reflector.get(PipesMetadata, found, route);
    const useGuards = this.reflector.get(GuardMetadata, found, route);
    const useInterceptors = this.reflector.get(InterceptorMetadata, found, route);
    const useFilters = this.reflector.get(FilterMetadata, found, route);
    if (useGuards) {
      callGuardsToCheck(useGaurds.guards);
    }
    if (useInterceptors) {
      callInterceptors(useInterceptors.interceptors);
    }
    if (usePipes) {
      callPipes(usePipes.pipes);
    }
    if (useFilters) {
      bindFilters(useFilters.filters);
    }
    this.httpAdapter[route.method ?? 'use'](`${found.route}/${route.route}`, (req, res, next) => next(found[route.name](metadataFromParameters(req)));
  }
}

我保证,这比代码库中的任何内容都更混乱和肮脏。

但它说明一旦控制器的路由处理程序方法被调用(found[route.name]()),那么在控制器的 return 返回之前,请求不在 Nest 的手中,所以它不能将管道绑定到服务。


综上所述,您可以自己从 class-transformer 导入 transform 并从 class-validator 导入 validate 和 运行 验证。除了管理对这些调用并跳过对原语的调用外,管道​​没有做任何特别的事情