Sharing about modules and modules in Nestjs

Modules in Nestjs

root module

  • After the project is created, nestjs will have a root module by default, that is: src/app.module.ts

    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    
    @Module({
        imports: [],
        controllers: [AppController],
        providers: [AppService],
    })
    export class AppModule {}
    
  • This is also how nestjs assembles applications. In the @Module decorator, the following parameters can be passed in

    • import can import other modules
    • controllers declare our controllers here
    • providers are used to declare our services
    • Actually there is one more option available: exports, example: exports: []
    • exports is used to expose submodules in our current module
  • If the project is relatively small, only one root module is needed. If the project is large, all modules are placed in one root module.

  • It will be inconvenient to maintain, and the amount of code will be too long. At this time, the code reviewer will trouble you.

  • We recommend splitting the project into different modules for maintenance, Angular does this, so Nestjs absorbs its advantages

Create submodules

  • If we split the application into three modules
    • Background application (server-side rendering)
    • Foreground application (server-side rendering)
    • api interface (interface service provided to App)
  • At this time, we have to split the modules according to the scene.
  • Create submodules separately:
    • $ nest g module module/admin background
    • $ nest g module module/default foreground
    • $ nest g module module/api interface
  • We can now see that in the root module, several major modules are automatically introduced
    import { Module } from '@nestjs/common';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    import { AdminModule } from './module/admin/admin.module';
    import { DefaultModule } from './module/default/default.module';
    
    @Module({
        imports: [AdminModule, DefaultModule], // Mainly see here
        controllers: [AppController],
        providers: [AppService],
    })
    export class AppModule {}
    
  • Then you will see the directories of three modules under src/module. At this time, the modules are defined.

Create a controller under the module

  • We also need to define related controllers, such as creating user and news controllers under the admin module
  • $ nest g controller module/admin/controller/user
  • After creation, we can under the admin module: src/module/admin/admin.module.ts file
  • You can see that the controller has been automatically introduced, and the admin module: admin.module.ts itself exposes the AdminModule
  • And AdminModule is mounted by the root module: src/app.module.ts (imports), so we can split and manage modules according to this idea
  • And our current user.controller.ts controller will also take effect, let's write a little bit of code
    // src/module/admin/controller/user/user.controller.ts
    import { Controller, Get } from '@nestjs/common';
    
    @Controller('admin')
    export class UserController {
        @Get('user')
        index() {
            return 'I'm admin in the module user controller';
        }
    }
    
    /*
    // Or the following can also be written
    @Controller('admin/user')
    export class UserController {
        @Get()
        index() {
            return 'I am the user controller in the admin module';
        }
    }
    */
    
  • Run it and see the effect, $ npm run start:dev
  • Visit: http://localhost:3000/admin/user
  • You can see the effect of what we wrote
  • Of course we can continue to create other controllers under admin: $ nest g controller module/admin/controller/news
  • The advantage of this split is that our project is big, it is very clear and easy to maintain
  • Similarly, other modules can continue to be added and maintained as described above

Create a service under a module

  • $ nest g service module/admin/user, this time similar to the controller, the newly created service will also be injected by the Admin module
    // src/module/admin/admin.module.ts
    import { Module } from '@nestjs/common';
    import { UserController } from './controller/user/user.controller';
    import { UserService } from './service/user/user.service';
    
    @Module({
        controllers: [UserController],
        providers: [UserService], // Mainly see here
    })
    export class AdminModule {}
    
  • We write some simulation code in the newly added service
    // src/module/admin/serice/user/user.serice.ts
    import { Injectable } from '@nestjs/common';
    
    @Injectable()
    export class UserService {
        // Simulate query database operations
        getUser() {
            return [
                {name: 'n1', age: 1},
                {name: 'n2', age: 1},
                {name: 'n3', age: 1},
            ]
        }
    }
    
  • To use this service, first introduce the service module in the corresponding controller, refer to:
    // src/module/admin/controller/user/user.controller.ts
    import { Controller, Get } from '@nestjs/common';
    import { UserService } from '../../service/user/user.service'
    
    @Controller('admin')
    export class UserController {
        constructor(private userService:UserService) {
        }
    
        @Get('user')
        index() {
            const list = this.userService.getUser()
            console.log('list', list)
            return 'I'm admin in the module user controller';
        }
    }
    
  • So what about public service reuse?

Public Service

  • Generally speaking, the methods in the top-level src/app.service.ts want to be used in the controller of the admin module
  • At this point, we need to do two steps
    • 1) Introduce the module AppService exposed by src/app.service.ts in the admin module
      // src/module/admin/admin.module.ts
      import { Module } from '@nestjs/common';
      import { UserController } from './controller/user/user.controller';
      import { UserService } from './service/user/user.service';
      import { AppService  } from 'src/app.service'; // pay attention here
      
      @Module({
          controllers: [UserController],
          providers: [UserService, AppService], // pay attention here
      })
      export class AdminModule {}
      
    • 2) In the corresponding controller, handle the reference and call
      import { Controller, Get } from '@nestjs/common';
      import { UserService } from '../../service/user/user.service'
      import { AppService  } from 'src/app.service'; // Note the introduction here
      
      @Controller('admin')
      export class UserController {
          constructor(private userService:UserService, private appService:AppService) {
          }
      
          @Get('user')
          index() {
              const list = this.userService.getUser()
              console.log('list', list)
              console.log(this.appService.getHello()) // look here
              return 'I'm admin in the module user controller';
          }
      }
      
  • If you don't want to use the root service, then we need to create a public service directory to manage the corresponding reuse methods

Create public modules based on catalogs for managing public services

  • For example: src/module/common directory, create a common module: $ nest g module module/common
  • Create common service in common module $ nest g service module/common/service/base
  • In this public service, write some methods for mock calls from other modules
    // src/module/common/service/base/base.service.ts
    import { Injectable } from '@nestjs/common';
    
    @Injectable()
    export class BaseService {
        getList() {
            return [
                {name: 'l1', age: 2},
                {name: 'l2', age: 2},
                {name: 'l3', age: 2},
            ]
        }
    }
    
  • At this time, I want to call the getList method in the admin module, what do I need to do?
  • TODO

Tags: Front-end Javascript node.js programming language

Posted by Andy17 on Mon, 11 Jul 2022 06:57:45 +0930