I am a Node.js intern. After entering the Dasoo car, I was lucky to see the framework of Akyuu.js. But the framework uses Express + Callback, which I don’t like very much. With my recommendation and the development of the community, the group leader decided to try TS + Async/Await. Therefore, I also went to learn about the backend framework of TS. As a result, AFTER being recommended by others, I found the nest.js framework with almost the same idea as mine.

Introduction of framework

Since THIS is not a tutorial, I won’t go into details. Check out nest.js. From my perceptual point of view, I will briefly talk about the following characteristics:

  • Decentralized routing. All routes are bound to the Controller through the decorator. Simple, clear, low learning cost.
  • The TypeScript/Rx. Js. Intelligent completion, code analysis, static typing and so on. If you’re just using it for personal use, it might feel complete. However, it is a great advantage to use it in enterprises.
  • Dependency injection. Learned from Angular, simplified, but sufficient. For example, dePS has been simplified.
  • Modular ideas. The Back-end frameworks of the Node community are actually oriented towards the middleware model by Express. Nest.js, on the other hand, borrows module ideas from Angular. Different services, Controllers, and Components form different modules. Modules can depend on each other or exist independently, which greatly reduces the complexity of testing and logic.
  • Easy to expand. With old frameworks, all you could do was write business logic, and you couldn’t do much else. Therefore, the traditional backend framework has to introduce a set of plug-in mechanism to enhance the extensibility of the framework. But Nest.js has the functionality of plug-ins built directly into the framework. A traditional plug-in here can be thought of as a module, loading different modules to add different functions.
  • Express cornerstone. Some would say, isn’t Koa a better model now? The Onion model solves more complex problems. Yeah, I don’t disagree with that. However, I would say that Express is still the simplest and most versatile method, as it is not a Generator/Promise and you just need to have a Node.js runtime environment that supports Callback. There’s no Node.js environment that doesn’t support Callback, anyway. Express has a much wider coverage than Koa.
  • All roads lead to Rome. So somebody said, what do I do to implement the Onion model? I mean, there’s always a way. In nest. js, the Onion model can be well implemented by Interceptor. This means that you can use Interceptor to keep track of request times.
  • Synchronize the code. Synchronous code is not just async/await. In many frameworks that support async/await, if you want to return a value, if it’s Express, you still need to callresp.send(await getValue()), and KOA also needs to be calledctx.body = await getValue(). But in Nest.js, you just need toreturn await getValue()Can. Achieve true synchronous writing of business logic code.
  • Logical layering. In fact, many functions can be achieved through middleware. However, different types of functions have different requirements. If only implemented through middleware, it is bound to lead to some repetitive code. So Nest. Js introduced inside Pipe/Interceptor/apps/ExceptionFilter logic layer. Different layers handle similar things, such as pipes, which handle transformations of input data. Interceptor implements the Onion model. Guard is used for interception tasks such as permission verification. ExceptionFilter is used to process error data. The benefit of this layering is that the code is much clearer, and the master needs to think about what needs to be done at this layer rather than at the middleware level.
  • The Validation. Come with checksum, and with TS very perfect, very comfortable to use, see the tutorial
  • Conversion of input parameters. This is actually a very convenient aspect. When you need to convert an input parameter to a class, you can use Validation to do the conversion. If you don’t want to use automatic conversion, you can use the traditional manual conversion method.
  • The test function is perfect. Because of dependency injection, testing is incredibly simple. And the official also provides a series of testing tools, can also be a good solution to the problem of unit testing.

Problems with the corporatization of Nest.js

  • The directory has no constraint. In the enterprise, not constraining directories leads to increasingly messy code. This reduces code maintainability.
  • No configuration management function. Configuration is often an important feature in framework development. For example, configure the database connection and configure the listening port.
  • No process management. Although it is provided@nestjs/cliBut this provides only the ability to create a project.
  • Some documents are not detailed, which will raise the threshold of entry.

Overall, though, the above points are just what makes Nest.js flexible. But we really in the development, or need a reasonable constraint to ensure the unity of development.

The attempt of Nest. Js as an enterprise

So we here for the above several problems, try to use some ways to carry out constraints.

The directory structure

We specify the following rules for projects:

  • All written in TypeScript and all locatedsrcdirectory
  • The entry file ismain.tsLeave the file untouched unless there are special circumstances
  • The configuration insrc/configfolder
  • All of the Service/Controller/Logic/Component is mounted toMainModuleUnder.
  • Among themmoduleFolders hold custom modules, or those that want to be separate but are not yet completely separate. The directory structure is similar to the project directory structure
  • bootThe folder is executed when the project is started, which is not given in Nest.js. I’m going to add this feature here, but I haven’t figured out how to implement it yet, so it’s up in the air.
  • interface/enumSuch data is exported with the corresponding service. Do not specify otherwise. For instancecar.service.tsIn addition to being able to exportCarServiceIn addition to class, you can also exportCarTypeEnum.
  • destFolders are compiled files that can be entered directlynode dest/main.jsRun.
  • Naming rules
    • All files except main.ts and class files have type suffixes, for exampleuser.model.ts car.controller.ts google.logic.ts. But let’s say just oneCarClass, so you can just name itcar.ts
    • Not allowed throughexport defaultExport data. On the one hand, to facilitate the import of the unified name, on the other hand, you can export interface/enum at any time.
    • All test files are suffixed with.spec.ts.test.tsAt the end.
|-- dest
    |--- ...
|-- src
    |-- config
    |-- controller
    |-- model
    |-- service
    |-- logic
    |-- component
    |-- boot
    |-- module
        |-- module-name
            |-- config
            |-- index.ts
            |-- module-name.module.ts
    |-- main.ts
    |-- main.module.ts
Copy the code

Configuration management

My current tentative idea is to expose a ConfigService by providing a ConfigModule to provide configuration fetching and viewing.

In some cases, multiple levels of configuration may be required, module-level configuration, application-level configuration. ConfigService can then automatically merge these rules when it retrieves the configuration.

Process management

It’s been 18 years now. Are you really worthy of yourself without Docker? I’m obviously sorry. So we’ll leave it to Docker to manage the process. Including start, stop, restart, log, etc., all handed over to Docker.

The startup command can then be simplified to node dest/main.js.

So you might think that if a Docker environment assigns you two U’s, you’re wasting one U. Theoretically yes, then you can manage it by yourself via PM2 etc., hahaha, no matter.

Iron.js

With all that said, and all that settling down, I had to give him a name, so I chose Iron. Why is it called Iron? Because of Iron Man. So why Iron Man? Because the armor he made can be disassembled, self-assembled. It suits our project very well.

But it depends on my mood when the project will settle down. But set a timeline, end of April, and get it done.

The biggest problem is configuration, which requires deep dependency injection, so it will be troublesome. But other aspects are more of a constraint.

That’s what I’ve learned from a week of using Nest.js. That’s all FOR now. I’ll talk more about it later.

Finished writing sleep, promised female ticket, la la la ~