如何在nestjs中返回自定义状态代码?

Dan*_*nik 1 api http-status-codes node.js typescript nestjs

我的系统有这样的自定义错误:

import { ExtendableError } from './extandable.error'

export const customError = {
  EMAIL_EXIST: () => new ExtendableError({
    message: 'USER WITH SUCH EMAIL ALREADY EXIST',
    code: 403
  }),

  INVALID_EMAIL: () => new ExtendableError({
    message: 'INVALID EMAIL',
    code: 400
  }),

  INVALID_PASSWORD: () => new ExtendableError({
    message: 'INVALID EMAIL OR PASSWORD',
    code: 403
  }),

  EMAIL_DOES_NOT_EXIST: () => new ExtendableError({
    message: 'EMAIL DOES NOT EXIST',
    code: 404
  }),

  TOKEN_DOES_NOT_EXIST: () => new ExtendableError({
    message: 'TOKEN DOES NOT EXIST',
    code: 404
  }),

  DIFFERENT_PASSWORDS: () => new ExtendableError({
    message: 'PASSWORDS ARE NOT SAME',
    code: 400
  }),

  CURRENT_PASSWORD_ERR0R: () => new ExtendableError({
    message: 'CURRENT PASSWORD IS INCORRECT',
    code: 400
  }),

  SAME_PASSWORDS_ERROR: () => new ExtendableError({
    message: 'CANNOT CHANGE SET NEW PASSWORD AS OLD PASSWORD',
    code: 403
  })
}
Run Code Online (Sandbox Code Playgroud)

在这里我可以编写自己的错误响应当我请求某些内容时,例如电子邮件存在,它会抛出一个错误,表明注册时此类电子邮件已存在。

它在这里指出:

async createAccount (doc: RegisterDto, verificationLink: string) {
      if (!isValidEmail(doc.email)) {
        return customError.INVALID_EMAIL()
      }

      const user = await this.existByEmail(doc.email)

      if (!user) {
        return customError.EMAIL_EXIST()
      }// HERE I RETURNING AN ERROR TO CONTROLLER
      doc.password = await bcrypt.hash(doc.password, SALT_ROUNDS)
      const created = await this.repository.create(this.registerMapper.toDomain(doc))
      await this.emailService.sendVerificationEmail(created, verificationLink)
      return created
    }
Run Code Online (Sandbox Code Playgroud)

这是我在控制器中的功能:

@Post('/api/register')
    async register(@Body() registerDTO: RegisterDto, @Request() request, @Response() response) {
      const verificationLink = `${request.protocol}://${request.header.host}/api/verify-account/`
      return await this.service.createAccount(registerDTO, verificationLink)
    }
Run Code Online (Sandbox Code Playgroud)

在邮递员中,它向我显示了正文和响应,但状态代码的实际结果有201代码 我该如何修复它? 邮递员回复

Pha*_*kul 5

试试这个(参考:https: //docs.nestjs.com/controllers#library-specific-approach

import { Controller, Get, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Controller('route01')
export class MyController {
  @Get('testResponse')
  async testFuntion(@Res() response: Response) {
     
     if('some condition') {
        return response.status(HttpStatus.OK).send(data);
     } else {
        return response.status(HttpStatus.BAD_REQUEST).send(data);
     }
  }
}

Run Code Online (Sandbox Code Playgroud)

如果您需要自定义函数来创建自己的响应,您也可以使用服务来创建,但也需要将响应传递给函数,如下所示

import { HttpStatus } from '@nestjs/common';
import { Response } from 'express';

service1(response: Response, data: any) {
  return response.status(HttpStatus.OK).send(data);
}
Run Code Online (Sandbox Code Playgroud)
@Controller('newcc')
testFuntion(@Res() response: Response) {
  const myCustomResp = this.service1(response, 'some data')
}
Run Code Online (Sandbox Code Playgroud)