Some time ago, our front-end infrastructure team launched a redirection management system — it provides the creation and maintenance of QR codes and short links.

This is a full-stack project developed by the front end team: the front end uses React and the back end uses Nestjs. We will get some practical experience and thinking in the process of development, take this opportunity to discuss with you. Also hope that through this sharing, so that we have a preliminary understanding of NestJS.

The theme

This sharing mainly includes four contents

  • What is nestJS?
  • Application scenarios and capabilities, what problems can be solved?
  • Why did you choose it? What are its advantages?
  • How to get started?

What

Let’s answer the first question: what is nestJS? Here is a definition from the official website:

Nest is a framework for building efficient, scalable Node.js server applications… It uses progressive JavaScript and has built-in and full TypeScript support

From the definition, let’s find a few keywords to look at:

  • Node-based: front-end friendly
  • Server application framework: mainly used for server interface development
  • Efficient and scalable: The architecture embodied in Nest’s functional modules is decoupled and easily combined
  • Progressive: You do not need to master all functions and features at the beginning. You can gradually add functions based on service requirements.
  • Nest was developed by TS and fully supports TS

Simply put, Nest is a Node server framework with many features.

When

Second question: What are the application scenarios and capabilities? What problem does it solve?

  1. The first is the most basic, do server-side development;

  2. Secondly, the extension of server functions, such as: security, authentication, queue, log, etc

  3. Technical architecture level support: microservices, serialization, and more

The above scenarios, the official provide mature solutions, technology selection is also a reliable guarantee.

Why

With Nest in mind, let’s talk about: Why Nest? Let’s briefly review the evolution of the Node Web framework, which I’ve divided into start-up and scale stages:

It started with node.js in 2009, followed by Express and Koa. They feature lightweight, minimalist frames

  • Their development styles are free and open, and as a result, everyone has their own set of development styles (different layers, project structures, file naming).
  • Framework features are too specific or even simple, and team projects rarely use them directly; Like JQuery on the Web, they are still powerful, but no longer capable of meeting complex development needs

From this background came Egg and Nest — enterprise apps and team collaboration, right out of the box

Nest vs. Egg

The functions of Express and Koa are basic. Nest and Egg are the two schemes we mainly consider. We compare them in the following aspects:

  • Community ecology: Nest is a thriving community with official solutions; Egg has a marketplace of plugins, but the quality of plugins is uneven
  • Nest has 42,000 Stars on GitHub, Egg 18,000 (as of January 2022);
  • Project update frequency: Nest is higher, Github issue feedback is timely, better user experience
  • Architecture design: code organization is more reasonable — project structure is divided according to functional modules; Decorator syntax is more elegant; Low coupling of code based on dependency injection; Egg advocates convention over configuration and lacks some flexibility
  • Nest supports TS natively
  • Difficulty: Nest concept more, slightly more difficult
  • Nest has a standardized development process for maintenance costs, which helps to maintain the uniformity of projects in the long run

Based on the above aspects, we believe that Nest design is more reasonable and more suitable for our team

At Alibaba’s D2 conference last December, the company also unveiled a new Node Web framework: MidWay. The overall design is similar to Nest: decorator support, DI based design, TS support — egg.js seems to have done its part in passing the baton to Midway

How

Next, at the code level, how to get started with Nest

The scaffold

  • Nest officially provides scaffolding, which can be installed globally through NPM. The use method is similar to Vue Client, and the development experience is relatively good
  • useNest CLISetting up new projects is very simple, passnest new xxxOne-click creation generates boilerplate code and installs dependencies
  • Using the commandnpm start:devStart the application and listen for inbound HTTP requests.

The directory structure

The initialized project contains some boilerplate files. Look at the SRC directory, which contains several core files

main.ts

Main. ts is the entry file for the application, which contains an asynchronous function: creating an app instance, starting and listening to the server. Internally, app.module — the module file — is a core Nest concept

Basic concept

module

  • Module, as it is called in Chinese, is the smallest unit of functional functionality in Nest.

  • So for example, in our application we haveUser management, order managementEach function can be independently formed into a module. In the figure below, the dotted line represents the server application, where the user management function isUserModule, order management isOrderModuleThe application consists of a number of moudule modules… There’s another one in front of themAppModuleIs the entire applicationThe root module.

  • The structure of the whole module is similar to the front-end SPA application: the front-end application APP is mounted to the root node, and files in the Pages directory are mapped to different page components
  • To create a basic module, we will use classes and decorators

A decorator

  • Decorators are a special syntax for modifying or enhancing classes, functions, objects, etc@expression, was the first to support this syntax in TS
  • expressionThe expression must be evaluated as a function, which is called at run time; The embellished body is passed in as a parameter.
  • The AppModule class is preceded by a new one@Module()Decorator that returns a module class and provides metadata (context and dependencies) for the module.

Controller and Service are introduced in app.module.ts. Let me introduce Controller by following the code’s dependencies

controller

  • Controller, which handles incoming requests and returned responses.
  • Like a dispatcher, it receives HTTP requests and then invokes the hit method via a routing distribution mechanism
  • @GetThis request type decorator can accept a routing address. If the route matches, it is calledgetHelloMethods; This is empty. It matches the root path
  • The controller is responsible for processingHTTPRequest, while delegating more complex tasks to providers, services (providers),What is Service?

Service

  • In Nest, a service is a common Provider that handles basic, common methods, such as handling business logic, interacting with databases… Providers are injected into controllers through dependency injection, and these methods are called by controllers.

I’ve just introduced you to the three core concepts of Nest

  • A module is the smallest unit in Nest, and many, many units make up the application. You can also think of it as a container, as shown below, where each module contains a controller and a provider

  • Controller processingHTTPRequest, distribute routes; Call the provider’s methods;
  • The basic/common logic is defined in the provider

Note that:

  • To avoid splitting logic across files during development, be careful to distinguish between controller and provider boundaries,

That is:

  • The Controller handles requests and distributes routes. Note that multiple providers can be called from a controller;
  • The underlying business logic is handled in the provider

The following code… This layer of functionality ensures clear and uniform code

Nest also has middleware (executed before and after routing programs), exception filters (exceptions thrown by handlers), guards (permission checks)… To develop some common functions. But I didn’t put them into the core Nest concepts, so you can read about them later.

Dependency injection

It’s often said that Nest is scalable and low-coupled, so how does it work? The answer is dependency injection

Dependecy Injection is a way to achieve low coupling (also known as design mode) that separates object creation from object consumption. The required dependencies are not created internally, but are transparently passed externally

Here is a piece of code that contains two classes: the first is the Engine and the second is the Car

  • Engine has an cylinders property that specifies the Engine type, and I’ll give it a set property which is internal combustion Engine
  • The Car constructor instantiates an engine through new, uses the class attribute of the engine in the Drive method, and returns the string: this is an internal-combustion engine Car
  • One day, I decided to change Engine so that instead of having a fixed type, I passed it in dynamically through a constructor. Then, Car also needs to change the code in the constructor. So it doesn’t meet the low coupling criteria.

So what if we use dependency injection?

  • In cars, Engine objects are passed directly through constructors rather than being created internally
  • In the external main method, when Car is instantiated, the Engine object is also instantiated and passed into the Car; This process is called injection; Notice that Engine is passed into Car;
  • So that no matter how the Engine logic changes, it doesn’t affect the Car code

Looking back, how is DI applied in Nest?

  • Back to the Module file,@ModuleIt’s declared in the decoratorcontrollersproviders.@ModuleThe decorator actually replaces the main function. Will be instantiatedControllerProviderAnd inject the Provider into the Controller

  • So in Controller you can call service through this.

In Nest, the provider is injected into the Controller, so the provider’s decorator name is Injectable

This is why Nest achieves low coupling of modules through dependency injection at the framework level, thus improving the extensibility of code.

Summary

Through the above explanation of Nest, a brief summary can be made:

First, we mainly introduce Nest from four aspects: What,When,Why and How

Second, Nest has some drawbacks: it has a lot of concepts; Design patterns are different than usual; There are few domestic developers;

Overall, I found Nest.js to be an “elegant, standardized, and extensible” Node framework. In the process of use, in addition to knowing how to use this device, we can gradually learn the back-end development mode, and the design advantages of Nest are also worth learning and exploring.