使用具有表单数据(Fastify)的 Nestjs 验证管道时超出最大调用堆栈大小

问题描述 投票:0回答:1

由于所有者刚刚在 GitHub 上关闭了我的问题,并且官方 Discord 服务器上的人员无法帮助我,所以我在这里试试运气。

由于 NestJS 没有用于 fastify(用于文件上传)的拦截器或其他任何东西,我想使用 fastify-multipart (现在为 @fastify/multipart)包。我以正常方式注册了中间件,但我使用了 AttachFieldsToBody 选项,因此我可以正确使用我设置为全局的验证管道。我有一个非常简单的 DTO 设置来满足我的发布请求。如果您让沙箱容器运行,您将看到 500 错误,指出验证管道中发生的最大调用堆栈超出。

GitHub 问题:https://github.com/nestjs/nest/issues/9683

沙箱:https://codesandbox.io/s/nestjs-fastify-multipart-bug-17m5ls

多部分中间件工作正常(尽管 Discord 上有人认为这是一个问题,假设我没有用谷歌搜索它)。唯一的问题是验证管道,但我无法追踪它,我不确定为什么它会导致无限循环。当我调试和查看通用包源代码时,如果有人遇到此问题或有解决方案的想法,请告诉我。

nestjs stack-overflow fastify fastify-multipart
1个回答
0
投票

很久以前就提出了这个问题。但由于问题至今仍然存在,我很高兴分享我找到的解决方案......

这个问题在某种程度上与 fields 属性有关(没有真正探究原因 - 也许是“Circluar”?)。

  <ref *2> {
    type: 'file',
    fieldname: 'file',
    filename: 'test.pdf',
    encoding: '7bit',
    mimetype: 'application/pdf',
    file: FileStream {
      ...
    },
    fields: <ref *1> {
      id: {
        type: 'field',
        fieldname: 'id',
        mimetype: 'text/plain',
        encoding: '7bit',
        value: 'b93fce8c-a754-486a-a42f-ef7a79d2c895',
        fieldnameTruncated: false,
        valueTruncated: false,
        fields: [Circular *1]
      },
      file: [Circular *2]
    },
    _buf: null,
    toBuffer: [AsyncFunction: toBuffer]
  }

因此,我利用了 onFile 处理程序,并从分配中排除了“fields”属性。我的文件字段的值不再符合“keyValues”定义,因为它包含所有想要的元数据而不仅仅是流,但这基本上就是我正在寻找的......

app.register(fastifyMultipart, {
  attachFieldsToBody: 'keyValues',
  limits: {
    fileSize: 1000 * 1000 * 20,
  },
  async onFile(part: MultipartFile) {
    // file has to be consumed to resolve promise
    await part.toBuffer();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { fields, ...rest } = part;
    part.value = rest;
  },
});

© www.soinside.com 2019 - 2024. All rights reserved.