Simple realization of unified return data format request results

preface

When designing the return format of the route callback, consideration is given to how to unify the successes and failures of all interfaces. Now let’s do this with Nest’s exception filter and interceptor API

Post follow-up documents to facilitate further study of Nest Chinese documents


Abnormal filter

  • Nest’s built-in exception layer handles all exceptions thrown throughout the application. When an unhandled exception is caught, the end user receives a friendly response.

  • This can be understood as an intermediate layer that responds to the user when an exception occurs in our system.

# # #Copy the code
  • Exception filtering code

    /* all-exception.filter.ts */ / import {ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'; import * as moment from 'moment'; Import {Request, Response} from 'express'; @catch (HttpException) export class HttpExceptionFilter implements ExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const request = ctx.getRequest<Request>(); const status = exception.getStatus(); Const {message, code} = exception.getresponse () as any; response.status(status).json({ code: code || status, timestamp: moment().format('yyyy-MM-DD HH:mm:ss'), path: request.url, error: 'Bad Request', message, }); }}Copy the code
  • Is referenced in the mian. Ts file and registered

    /* main.ts */ import { HttpExceptionFilter } from './filters/http-exception.filter'; async function bootstrap() { ... // global register error filter app.useGlobalFilters(new HttpExceptionFilter()); } bootstrap();Copy the code
  • Failed to initiate the request in another file

    Import {HttpException} from '@nestjs/common'; // throw new HttpException(' request failed ', 500);Copy the code

    The effect

    • The token expiration event is triggered in JWT. The token expiration event can also be triggered in service Controller. Data processing trigger

The interceptor

  • Interceptors are classes annotated with the @Injectable() decorator. Interceptors should implement the NestInterceptor interface.

  • Interceptors have a set of useful features inspired by AOP techniques. They can: bind additional logic before/after function execution, convert results returned from a function, convert exceptions thrown from a function, extend basic function behavior, and completely rewrite the function based on selected conditions (for example, caching purposes)

  • Here we use the interceptor to do a transformr. Interceptor interceptor so that we don’t have to repeat the return format processing for each service

# # #Copy the code
  • Interceptor code

    /* transform.interceptor.ts */ import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; @Injectable() export class TransformInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( map((data) => { return { data, code: 200, message: 'Request successful ',}; })); }}Copy the code
  • Is referenced in the mian. Ts file and registered

    /* main.ts */ ... import { TransformInterceptor } from './interceptor/transform.interceptor'; async function bootstrap() { ... / / global registration blocker app. UseGlobalInterceptors (new TransformInterceptor ()); . } bootstrap();Copy the code
  • Use just retrun out of the route

    The effect

conclusion

  • So far we have done inNest.jsIs a basic encapsulation of the information returned by the request.
  • Want to know moreThe interceptorPlay students can go to the official documentsThe document

reference

  • Chinese Version of Nest