Modularization

  1. Reasonable nest architecture, create modules

    A well-structured architecture should employ multiple modules, each encapsulating a set of closely related functions. The function should contain controller, service, etc. Also, test files and test data files are placed here.

    Create module directive: nest g module module_name. This will create the module and automatically import the module file into the parent module. The structure is:

    1
    2
    3
    4
    5
    |--src
    |-- coffees module folder
    |-- coffees.module.ts //helps us keep our code organized and establish clear boundaries for the application and its functionality.
    |-- coffees.controller.ts
    |-- coffees.service.ts

  2. @Module decorator

    In the coffees.module.ts file, the decorator before the CoffeesModule class is @Module({}) . It provides data to support application structure. The module decorator requires a single object whose properties describe the module and all contexts.

    The attributes of the @Module decorator have four kinds of content:

    1. controllers: API root, we want this module to be instantiated.

    2. exports: List the providers in the current module, which should be available everywhere. This module will be imported.

    3. imports: Allows us to list other modules of this module.

    4. providers: an array. Lists services that need to be instantiated by the nest injector. Any provider here will only be available in this module unless it is added to the exports array.


  3. Incorporate the file into the module file

    Included in the file as attributes of the @Module decorator: [array].

    1
    2
    3
    4
    import {Module} from '@nestjs/common';

    @Module({controllers: [CoffeesController], providers: [CoffeesService]})
    export class CoffeesModule{}

Share