使用 FileInterceptor 上传文件时如何在 NestJs 中返回自定义状态代码?

RAJ*_*DIN 2 node.js nestjs

我正在尝试返回不同类型异常的自定义状态代码。尽管我正确地收到了响应,但我无法在不导致错误的情况下做到这一点。该错误仅发生在if 条件块内部(如果我在 post 请求中发送文件)。else 块中没有错误。

错误:检测到循环依赖性

// Below code gives this error =>  Error: cyclic dependency detected

import { Controller, Post, Req, Res, UseInterceptors, UploadedFile } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request, Response } from 'express';

@Controller('testing')
export class TestController {
    constructor() { }

    @Post('/upload')
    @UseInterceptors(FileInterceptor('file'))
    upload(@UploadedFile() file, @Res() response: Response) { 
        if (file && file !== undefined) {
            return response.status(200).json({
                status: "OK",
                message: "File Uploaded"
            });
        } else {
            return response.status(400).json({
                status: "BAD REQUEST",
                message: "File not found"
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rap*_*res 6

不久前我也遇到了类似的错误。

如果您确实想使用@Res,请尝试将其与参数一起使用passthrough保持与 Nest 标准响应处理的兼容性

像这样的东西(我做了一些重构以使其更干净)

    @Post("/upload")
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file, @Res({ passthrough: true }) res: Response) {
        if (file) {
            res.status(HttpStatus.OK).json({
                status: "OK",
                message: "File uploaded",
            });
        } else {
            res.status(HttpStatus.BAD_REQUEST).json({
                status: "BAD REQUEST",
                message: "File not found",
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

ps:并尝试使用HttpStatus枚举来使代码更具可读性

但有一个更好、更干净的解决方案。如果文件不存在,你只需要抛出一个BadRequestException带有你想要的消息,NestJS 就会神奇地为你处理一切=D

    @Post("/upload")
    @HttpCode(HttpStatus.OK)
    @UseInterceptors(FileInterceptor("file"))
    upload(@UploadedFile() file) {
        if (!file) {
            throw new BadRequestException("File not found!");
        }
        // do something with the file...
    }
Run Code Online (Sandbox Code Playgroud)