In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces what is the use of the AOP architecture of Node back-end framework Nest.js. It is very detailed and has a certain reference value. Interested friends must read it!
Nest.js is a back-end framework of Nodejs, which encapsulates http platforms such as express and solves the architecture problem. 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 mean here? Let's take a look at it separately:
MVC 、 IOC
MVC is the abbreviation of Model View Controller. Under MVC architecture, the request is first sent to Controller, which dispatches the Service of the Model layer to complete the business logic, and then returns the corresponding View.
Nest.js provides the @ Controller decorator to declare Controller:
Service declares it with the @ Injectable decorator:
The class declared by the @ Controller and @ Injectable decorators is scanned by Nest.js, creating corresponding objects and adding them to a container, all of which are automatically injected according to the dependencies declared in the constructor, that is, DI (dependency inject), an idea called IOC (Inverse Of Control).
The advantage of IOC architecture is that there is no need to manually create objects and pass them into constructors of different objects based on dependencies, everything is automatically scanned and created and injected.
In addition, Nest.js provides the capabilities of AOP (Aspect Oriented Programming), that is, aspect-oriented programming:
AOP
What does AOP mean? What is aspect-oriented programming?
A request may go through the logic of Controller (controller), Service (service), and Repository (database access):
How do I add some general logic to this call link? Such as logging, access control, exception handling and so on.
What is easy to think of is to directly transform the Controller layer code to add this logic. This is OK, but not elegant, because these general logic intrudes into the business logic. Can you transparently add logs, permissions and other processing to these business logic?
Is it possible to add a phase of executing general logic before and after calling Controller?
Like this:
Such horizontal extension points are called aspects, and this transparent way of programming with some aspect logic is called AOP (aspect-oriented programming).
The advantage of AOP is that it can separate some general logic into aspects and maintain the storage of business logic, so that aspect logic can be reused and can be dynamically added or deleted.
In fact, the onion model of Express middleware is also an implementation of AOP, because you can transparent the outer bread layer, add some logic, the inner layer is not aware of.
There are five ways for Nest.js to implement AOP, including Middleware, Guard, Pipe, Inteceptor, ExceptionFilter:,
Middleware Middleware
Nest.js can also use middleware based on Express, but it is further subdivided into global middleware and routing middleware:
Global middleware is the kind of middleware of Express, which adds some processing logic before and after the request, and each request goes here:
Routing middleware is for a particular route, and the scope is smaller:
This directly inherits the concept of Express and is easier to understand.
Let's take a look at some concepts of Nest.js extensions, such as Guard:
Guard
Guard means route guard. It can be used to determine permissions before calling a Controller, and return true or flase to decide whether to release:
The way to create Guard is as follows:
To implement the CanActivate interface and the canActive method in Guard, you can get the requested information from context, then do some permission verification and return to true or false.
Add it to the IOC container through the @ Injectable decorator, and then enable it in a Controller:
Controller itself does not need to make any changes, but transparently adds the logic of permission judgment, which is the advantage of AOP architecture.
And, just as Middleware supports global and routing levels, Guard can be enabled globally:
Guard can extract the access control logic of the route, but cannot modify the request and response. This logic can be used with Interceptor:
Interceptor
Interceptor means interceptor, and you can add some logic before and after the target Controller method:
The way to create Inteceptor is as follows:
To implement the NestInterceptor interface and the intercept method in Interceptor, calling next.handle () calls the target Controller, and you can add some processing logic before and after.
The processing logic before and after Controller may be asynchronous. They are organized through rxjs in Nest.js, so you can use various operator of rxjs.
Interceptor supports enabling each route individually, which only works on a controller, and also supports enabling globally, which works on all controller:
In addition to the permission control of the route and the processing before and after the target Controller, the processing of parameters is also a general logic, so Nest.js also extracts the corresponding aspect, that is, Pipe:
Pipe
Pipe means pipe, which is used to validate and transform parameters:
The way to create Pipe is as follows:
Pipe needs to implement the PipeTransform API and the transform method, in which you can verify the parameter value value passed in. For example, if the format and type are correct, an exception is thrown. You can also do a conversion and return the converted value.
There are eight Pipe built-in, and you can tell what they mean by their names:
ValidationPipe
ParseIntPipe
ParseBoolPipe
ParseArrayPipe
ParseUUIDPipe
DefaultValuePipe
ParseEnumPipe
ParseFloatPipe
Similarly, Pipe can be valid for only one route or for each route:
Whether it's Pipe, Guard, Interceptor, or the final called Controller, you can throw some exceptions during the process, so how do you respond to some kind of exception?
This exception-to-response mapping is also a general logic, and Nest.js provides ExceptionFilter to support:
ExceptionFilter
ExceptionFilter can handle the exception thrown and return the corresponding response:
The form of creating an ExceptionFilter is as follows:
First of all, to implement the ExceptionFilter interface and the catch method, you can intercept exceptions, but you still need to declare any exceptions with the @ Catch decorator. After intercepting the exceptions, you can exception the corresponding response and give users a more friendly prompt.
Of course, not all exceptions will be handled. Only exceptions that inherit from 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:
Nest.js implements the correspondence between exception and response in this way. As long as different HttpException is thrown in the code, the corresponding response will be returned, which is very convenient.
Similarly, ExceptionFilter can choose to take effect globally or a route:
A route:
Global:
We learned about the mechanisms of AOP provided by Nest.js, but what is the sequential relationship between them?
The order of several AOP mechanisms
Middleware, Guard, Pipe, Interceptor, and ExceptionFilter can all transparently add some processing logic to a route or all routes, which is the advantage of AOP.
But what is the sequential relationship between them?
The calling relationship depends on the source code.
The corresponding source code is as follows:
Obviously, when entering this route, Guard will be called first to determine whether there is permission, etc. If there is no permission, an exception will be thrown here:
The thrown HttpException is processed by ExceptionFilter.
If you have permission, it will call the interceptor, which organizes a chain, calls one by one, and finally invokes the controller method:
Before calling the controller method, you use pipe to process the parameters:
Each parameter is converted:
The timing of calling ExceptionFilter is easy to think of, which is to handle the exception once before the response.
While Middleware is a concept in express, Nest.js only inherits the next, which is called in the outermost layer.
This is the order in which these AOP mechanisms are called. To sort this out, even if you have a good grasp of Nest.js.
Summary
Nest.js makes a layer of encapsulation based on the http platform of express, and applies the architecture ideas of MVC, IOC, AOP and so on.
MVC is the division of Model and View Controller. The request first goes through Controller, then calls Service and Repository in the Model layer to complete the business logic, and finally returns the corresponding View.
IOC means that Nest.js automatically scans classes with @ Controller and @ Injectable decorators, creates their objects, and automatically injects the objects it depends on based on dependencies, eliminating the hassle of manually creating and assembling objects.
AOP is to extract the general logic and add it to a certain place through the way of section, which can reuse and dynamically add and delete section logic.
Nest.js 's Middleware, Guard, Interceptor, Pipe and ExceptionFileter are all implementations of AOP ideas, but they are all aspects of different locations, and they can all flexibly act on a route or all routes, which is the advantage of AOP.
We look at the order of their calls through the source code. Middleware is the concept of Express. In the outermost layer, after arriving at a certain route, Guard,Guard will be called to determine whether the route has permission to access, and then Interceptor will be called to extend some logic before and after Contoller. Before reaching the target Controller, Pipe will be called to verify and convert the parameters. All HttpException exceptions are handled by ExceptionFilter and return different responses.
Nest.js is through this AOP architecture, to achieve a loosely coupled, easy to maintain and expand the architecture.
Do you feel the benefits of AOP architecture?
The above is all the content of the article "what is the use of the AOP architecture of Nest.js, the Node back-end framework?" thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.