Encapsulation implementation of the data format returned by nestjs to the front end

Encapsulation implementation of the data format returned by nestjs to the front end

Generally, during the development process, the success or failure of the interface request is not determined based on the httpcode, but the code field is added based on the data returned by the request.

1. Comparison of returned data formats

1. Directly returned data format

{
  "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. Return data after we package it ourselves

{
 code: 0,
 message: "Request successful",
 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 unify the return format

1. Create a filter using the command

nest gf filters/httpException

2. Filter code

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, // custom 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 information response.status(status);
  response.header('Content-Type', 'application/json; charset=utf-8');
  response.send(errorResponse);
 }
}

3. Global registration in main.ts

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

async function bootstrap() {
 ...
 // Globally register error filters app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();

4. Test, returned error information

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

3. Unify the return data of successful request

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

2. Interceptor code

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 successful',
    };
   }),
  );
 }
}

3. Global Registration

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

async function bootstrap() {
 ...
 // Globally registered 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 successful"
}

This is the end of this article about the encapsulation implementation of the data format returned by nestjs to the front-end. For more relevant content about the data format returned by nestjs to the front-end, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Nest.js authorization verification method example
  • Detailed explanation of Nest.js environment variable configuration and serialization
  • How to use nest.js to provide multiple static directories using express

<<:  A brief discussion on the preliminary practice of Docker container interconnection

>>:  Nginx Location Configuration Tutorial from Scratch

Recommend

Summary of common functions and usage methods of WeChat applet development

Here, I have mainly sorted out some commonly used...

Use HTML and CSS to create your own warm man "Dabai"

The final result is like this, isn’t it cute… PS:...

Whitespace processing in HTML/CSS and how to preserve whitespace in the page

Whitespace rules in HTML In HTML, multiple spaces...

Implementation of building custom images with Dockerfile

Table of contents Preface Introduction to Dockerf...

JS Easy to understand Function and Constructor

Table of contents 1. Overview 1.1 Creating a func...

Javascript to achieve the drag effect of the login box

This article shares the specific code of Javascri...

How to use http and WebSocket in CocosCreator

Table of contents 1. HttpGET 2. HTTP POST WebSock...

mysql installer community 8.0.12.0 installation graphic tutorial

This tutorial shares the installation of mysql in...

Introduction to the use of anchors (named anchors) in HTML web pages

The following information is compiled from the Int...

Detailed explanation of how Vue components transfer values ​​to each other

Table of contents Overview 1. Parent component pa...

Detailed steps for installing and configuring MySQL 5.7

1. Download MySQL 1. Log in to the official websi...

How to use ss command instead of netstat in Linux operation and maintenance

Preface When operating and managing Linux servers...

Introduction to Linux compression and decompression commands

Table of contents Common compression formats: gz ...

TypeScript interface definition case tutorial

The role of the interface: Interface, in English:...