Encapsulation implementation of nestjs returning to front end data format

  • 2021-10-27 06:28:58
  • OfStack

In the development process, the success and failure of interface request will not be judged according to httpcode, but the data returned by the request will be added with code field

1. Comparison of data formats returned

1. Data format returned directly


{
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": " Husky 1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
}

2. The returned data after our own packaging


{
 code: 0,
 message: " Request succeeded ",
 data: {
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": " Husky 1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
 }
}

2. Intercept all error requests and return the format in a unified way

1. Use the command to create a filter


nest g f filters/httpException

2. Code for the filter


import {
 ArgumentsHost,
 Catch,
 ExceptionFilter,
 HttpException,
 HttpStatus,
 Logger,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
 catch(exception: HttpException, host: ArgumentsHost) {
  const ctx = host.switchToHttp();
  const response = ctx.getResponse();
  const request = ctx.getRequest();

  const message = exception.message.message;
  Logger.log(' Error prompt ', message);
  const errorResponse = {
   data: {
    error: message,
   }, //  Get all error messages 
   message: ' Request failed ',
   code: 1, //  Customize code
   url: request.originalUrl, //  Wrong url Address 
  };
  const status =
   exception instanceof HttpException
    ? exception.getStatus()
    : HttpStatus.INTERNAL_SERVER_ERROR;
  //  Set the returned status code, request header and send error message 
  response.status(status);
  response.header('Content-Type', 'application/json; charset=utf-8');
  response.send(errorResponse);
 }
}

3. Register globally in main. ts


...
import { HttpExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
 ...
 //  Filters for global registration errors 
 app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();

4. Test, return error message


{
 "statusCode": 400,
 "error": "Bad Request",
 "data": {
  "message": [
   {
    "age": " Required integer "
   }
  ]
 },
 "message": ' Request failed ',
 "code": 1,
 "url": "/api/v1/cat"
}

3. Unified 1 requests successful return data

1. Create an interceptor src/interceptor/transform. interceptor. ts

2. Code for the interceptor


import {
 Injectable,
 NestInterceptor,
 CallHandler,
 ExecutionContext,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Response<T> {
 data: T;
}
@Injectable()
export class TransformInterceptor<T>
 implements NestInterceptor<T, Response<T>> {
 intercept(
  context: ExecutionContext,
  next: CallHandler<T>,
 ): Observable<Response<T>> {
  return next.handle().pipe(
   map(data => {
    return {
     data,
     code: 0,
     message: ' Request succeeded ',
    };
   }),
  );
 }
}

3. Global registration


...
import { TransformInterceptor } from './interceptor/transform.interceptor';

async function bootstrap() {
 ...
 //  Global registration interceptor 
 app.useGlobalInterceptors(new TransformInterceptor());
 ...
}
bootstrap();

4. Test return data


{
 "data": {
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": " Husky 1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
 },
 "code": 0,
 "message": " Request succeeded "
}


Related articles: