Search code examples
nestjsclass-validatorclass-transformer

How should I create for nestjs response dto?


How should I create the dto for the nestjs response? I am currently creating the following code. I want to define it like the dto of input parameters.

■ response code like this

return {
    statusCode: 200,
    message: 'successs',
    data: {
        id: 10
    }
}

■ I want to do like this

async test: Promise<SuccessDto> {
    return respoinse: SuccessDto
}

Solution

  • I believe there is no need to do that. You can access the code through the headers and the convention is the following

    • 200 is ok / success,
    • 201 is created,
    • 204 is no response,
    • 400 is bad request,
    • 401 is unauthorized,
    • 403 is forbidden,
    • 404 is not found

    But to answer your question, it might be possible through interceptors. Their sandbox :

    https://github.com/nestjs/nest/blob/master/sample/21-serializer/src/app.controller.ts

    use the Res, create a DTO with a generic or a class to extends it and glue it together. Use the @Type(() => YourDTO) to expose what you need. But your kind of reinventing the wheel, NestJS takes care of it and you can overwrite the Response status if needed.