How to return custom status codes in NestJs while using FileInterceptor to upload a file?

Viewed 6067

I am trying to return custom status codes for different type of exceptions. Although I'm receiving response properly, I'm not able to do it without causing an error. The error occurs only inside if condition block (if I send a file in post request). There is no error in else block.

Error: cyclic dependency detected

// 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"
            });
        }
    }
}
1 Answers

I got a similar error a while ago.

If you really want to use the @Res, Try to use it with the passthrough argument to maintain compatibility with Nest standard response handling.

Something like this (I did some refactoring to make it a bit more clean)

    @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",
            });
        }
    }

p.s.: And try to use HttpStatus enum to keep your code more readble

But there is a much better and clean solution. You just need to throw a BadRequestException with the message you want if the file is not there, and NestJS will magically take care of everything for you =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...
    }
Related