search
HomeWeb Front-endJS TutorialUnderstand the AOP architecture of Node.js Nest.js and talk about its benefits

This article will take you to understand the AOP architecture of the back-end framework Nest.js and introduce the benefits of the Nest.js AOP architecture. I hope it will be helpful to everyone!

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsNest.js is a

Nodejs

back-end framework. It encapsulates http platforms such as express to solve architectural problems. It provides MVC, IOC, AOP and other architectural features that express does not have, making the code easier to maintain and expand. What do MVC, IOC, and AOP here mean? Let’s take a look at them respectively:

MVC, IOC

MVC is the abbreviation of Model View Controller. Under the MVC architecture, the request is first sent to the Controller, which dispatches the Service of the Model layer to complete the business logic, and then returns the corresponding View.

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsNest.js provides the @Controller decorator to declare the Controller:

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsAnd the Service will be decorated with @Injectable Decorator to declare:

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsClasses declared through @Controller and @Injectable decorators will be scanned by Nest.js, corresponding objects will be created and added to a container. All of these The object will be automatically injected according to the dependency declared in the constructor, which is DI (dependency inject). This idea is called IOC (Inverse Of Control).

The advantage of the IOC architecture is that there is no need to manually create objects and pass them into the constructors of different objects based on dependencies. Everything is automatically scanned, created, and injected.

In addition, Nest.js also provides the ability of AOP (Aspect Oriented Programming), which is the ability of aspect-oriented programming:

AOP

What is AOP What does it mean? What is aspect-oriented programming?

A request may go through the logic of Controller, Service, and Repository (database access):

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsIf you want to How to add some general logic to this call link? Such as logging, permission control, exception handling, etc.

The easy thing to think of is to directly transform the Controller layer code and add this logic. This works, but it's not elegant because these common logics invade the business logic. Can we transparently add logs, permissions, etc. to these business logics?

Is it possible to add a stage to execute common logic before and after calling the Controller?

For example:

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsSuch a horizontal expansion point is called an aspect, and this transparent programming method that adds some aspect logic is called AOP (aspect-oriented) programming).

The advantage of AOP is that it can separate some common logic into aspects and keep the business logic pure. In this way, the aspect logic can be reused and dynamically added and deleted

In fact, the onion model of Express's middleware is also an AOP implementation, because you can transparently wrap a layer on the outside and add some logic, and the inner layer will not be aware of it.

And Nest.js has more ways to implement AOP, there are five in total, including Middleware, Guard, Pipe, Inteceptor, ExceptionFilter:,

MiddlewareMiddleware

Nest .js can naturally use middleware based on Express, but it has been further subdivided into global middleware and routing middleware:

Global middleware is the middleware of Express. Before requesting and After adding some processing logic, each request will go here:

Understand the AOP architecture of Node.js Nest.js and talk about its benefits Routing middleware is for a certain route, with a smaller scope:

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsThis is a concept that directly inherits Express and is easier to understand.

Let’s look at some concepts of Nest.js extension, such as Guard:

Guard

Guard means routing guard, which can be used to determine permissions before calling a Controller. , return true or false to decide whether to release:

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsThe way to create Guard is as follows:

Guard needs to implement the CanActivate interface and the canActive method. It can get the requested information from the context, and then perform some permission verification and other processing before returning true or false.

Add it to the IOC container through the @Injectable decorator, and then enable it in a Controller:

Understand the AOP architecture of Node.js Nest.js and talk about its benefits

##The Controller itself does not need to be modified. But the logic of permission judgment is transparently added. This is the benefit of the AOP architecture.

And, just like Middleware supports global level and routing level, Guard can also be enabled globally:

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Guard can abstract the access control logic of routing, However, the request and response cannot be modified. This kind of logic can use Interceptor:

Interceptor

Interceptor means interceptor. You can add some logic before and after the target Controller method:

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

The way to create an Inteceptor is as follows:

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Interceptor To implement the NestInterceptor interface, implement the intercept method and call next.handle() The target Controller will be called, and some processing logic can be added before and after.

The processing logic before and after the Controller may be asynchronous. Nest.js organizes them through rxjs, so you can use various operators of rxjs.

Interceptor supports each route being enabled individually, which only affects a certain controller. It also supports global enablement, which affects all controllers:

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

In addition to routing permission control and processing before and after the target Controller, which are all common logic, the processing of parameters is also a common logic, so Nest.js also extracted the corresponding aspects, that is, Pipe:

Pipe

Pipe means pipeline, used to do some verification and conversion of parameters:

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

The way to create Pipe is like this :

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Pipe To implement the PipeTransform interface, implement the transform method, which can perform parameter verification on the incoming parameter value value, such as whether the format and type are correct. If it is not correct, then throw an exception. You can also perform conversion and return the converted value.

There are 8 built-in Pipes, and their meanings can be seen from their names:

  • ValidationPipe
  • ParseIntPipe
  • ParseBoolPipe
  • ParseArrayPipe
  • ##ParseUUIDPipe
  • DefaultValuePipe
  • ParseEnumPipe
  • ParseFloatPipe
  • Similarly, Pipe can only take effect on a certain route. It can also take effect for each route:

1Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsWhether it is Pipe, Guard, Interceptor or the Controller that is finally called, it can be used during the process Throw some exceptions, how to respond to certain exceptions?

This mapping of exceptions to responses is also a common logic. Nest.js provides ExceptionFilter to support:

ExceptionFilter

ExceptionFilter can handle thrown exceptions , return the corresponding response:

Understand the AOP architecture of Node.js Nest.js and talk about its benefitsThe form of creating ExceptionFilter is as follows:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefitsFirst, implement the ExceptionFilter interface, By implementing the catch method, you can intercept exceptions, but what exceptions you want to intercept need to be declared with the @Catch decorator. After intercepting the exception, you can respond with the exception corresponding to give the user a more friendly prompt.

Of course, not all exceptions will be handled. Only exceptions that inherit HttpException will be handled by ExceptionFilter. Nest.js has many built-in subclasses of HttpException:

  • BadRequestException
  • UnauthorizedException
  • NotFoundException
  • ForbiddenException
  • NotAcceptableException
  • RequestTimeoutException
  • ConflictException
  • GoneException
  • PayloadTooLargeException
  • UnsupportedMediaTypeException
  • UnprocessableException
  • InternalServerErrorException
  • NotImplementedException
  • BadGatewayException
  • ##ServiceUnavailableException
  • GatewayTimeoutException
Of course, you can also extend it yourself:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Nest.js is implemented in this way With the corresponding relationship between exceptions and responses, as long as different HttpExceptions are thrown in the code, the corresponding responses will be returned, which is very convenient.

Similarly, ExceptionFilter can also choose to take effect globally or take effect on a certain route:

A certain route:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Globally:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

We understand the AOP mechanism provided by Nest.js, but what is their sequential relationship?

The order of several AOP mechanisms

Middleware, Guard, Pipe, Interceptor, and ExceptionFilter can all transparently add certain processing logic to a certain route or all routes. This is the benefit of AOP.

But what is the sequential relationship between them?

The calling relationship depends on the source code.

The corresponding source code is like this:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

#Obviously, when entering this route, Guard will be called first to determine whether there is permission, etc., if not Permissions, an exception is thrown here:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

The HttpException thrown will be handled by ExceptionFilter.

If you have permission, the interceptor will be called. The interceptor organizes a chain, calls one by one, and finally calls the controller method:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Before calling the controller method, pipe will be used to process the parameters:

2Understand the AOP architecture of Node.js Nest.js and talk about its benefits

Each parameter will be converted:

Understand the AOP architecture of Node.js Nest.js and talk about its benefits

The calling timing of ExceptionFilter is easy to think of, which is to handle the exception before responding.

And Middleware is a concept in express. Nest.js just inherits it, and it is called at the outermost layer.

This is the calling sequence of these AOP mechanisms. Once you have these things sorted out, you will have a good grasp of Nest.js.

Summary

Nest.js is a layer of encapsulation based on the express http platform, and applies MVC, IOC, AOP and other architectural ideas.

MVC is the division of Model and View Controller. The request first passes through the Controller, then calls the Service and Repository of the Model layer to complete the business logic, and finally returns the corresponding View.

IOC means that Nest.js will automatically scan classes with @Controller and @Injectable decorators, create their objects, and automatically inject the objects it depends on based on dependencies, eliminating manual creation and assembly. Object trouble.

AOP extracts general logic and adds it to a certain place through aspects. It can reuse and dynamically add and delete aspect logic.

Middleware, Guard, Interceptor, Pipe, and ExceptionFileter of Nest.js are all implementations of AOP ideas. They are just aspects at different locations. They can all be flexibly applied to a certain route or all routes. This is Advantages of AOP.

We looked at their calling sequence through the source code. Middleware is the concept of Express. In the outermost layer, after reaching a certain route, Guard will be called first. Guard is used to determine whether the route has permission to access, and then The Interceptor will be called to extend some logic before and after the Controller. Before reaching the target Controller, the Pipe will be called to verify and convert the parameters. All HttpException exceptions will be handled by ExceptionFilter and return different responses.

Nest.js uses this AOP architecture to achieve a loosely coupled, easy to maintain and expand architecture.

Have you felt the benefits of AOP architecture?

For more node-related knowledge, please visit:

nodejs tutorial!

The above is the detailed content of Understand the AOP architecture of Node.js Nest.js and talk about its benefits. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

怎么使用pkg将Node.js项目打包为可执行文件?怎么使用pkg将Node.js项目打包为可执行文件?Jul 26, 2022 pm 07:33 PM

如何用pkg打包nodejs可执行文件?下面本篇文章给大家介绍一下使用pkg将Node.js项目打包为可执行文件的方法,希望对大家有所帮助!

一文解析package.json和package-lock.json一文解析package.json和package-lock.jsonSep 01, 2022 pm 08:02 PM

本篇文章带大家详解package.json和package-lock.json文件,希望对大家有所帮助!

分享一个Nodejs web框架:Fastify分享一个Nodejs web框架:FastifyAug 04, 2022 pm 09:23 PM

本篇文章给大家分享一个Nodejs web框架:Fastify,简单介绍一下Fastify支持的特性、Fastify支持的插件以及Fastify的使用方法,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

手把手带你使用Node.js和adb开发一个手机备份小工具手把手带你使用Node.js和adb开发一个手机备份小工具Apr 14, 2022 pm 09:06 PM

本篇文章给大家分享一个Node实战,介绍一下使用Node.js和adb怎么开发一个手机备份小工具,希望对大家有所帮助!

图文详解node.js如何构建web服务器图文详解node.js如何构建web服务器Aug 08, 2022 am 10:27 AM

先介绍node.js的安装,再介绍使用node.js构建一个简单的web服务器,最后通过一个简单的示例,演示网页与服务器之间的数据交互的实现。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools