


Understand 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!
Nest.js is a
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.
Nest.js provides the @Controller decorator to declare the Controller:
And the Service will be decorated with @Injectable Decorator to declare:
Classes 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).
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):
If 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:
Such a horizontal expansion point is called an aspect, and this transparent programming method that adds some aspect logic is called AOP (aspect-oriented) programming).
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:
Routing middleware is for a certain route, with a smaller scope:
This 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:
The 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:
- ValidationPipe
- ParseIntPipe
- ParseBoolPipe
- ParseArrayPipe
Whether 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:
The form of creating ExceptionFilter is as follows:
First, 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
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:
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.