Project structure

  1. Create a project

    First create the src folder in the project folder, then create the entry file index.js in it, then run npm init -y .

    Then install express, dotenv, cors, morgan, Mongoose packages. npm i express dotenv cors morgan mongoose. morgan can show which requests are sent to the server.


  2. Project Structure (Orientation 1)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    --package.json
    --package-lock.json
    --src
    |-- index.js //Entry file (server.js, app.js)
    |-- routes
    |-- tasks.js //(task router) (or named task.routes.js)
    |-- users.js //(user router) (or named users.routes.js)
    |-- index.js //(Import all the routers above and make a unified export)
    |-- controllers // (logical processing part)
    |-- tasks.js //(task Controller) (or named tasks.controllers.js)
    |-- users.js //(user Controller) (or named users.controllers.js)
    |-- models
    |-- tasks.js //(task Controller) The format design of the task data in the database. Used for ORM (object relational mapping, used to interact with the database).
    |-- middleware
    |-- error-middleware
    |-- xxxErrorHandler.js
    |-- authGuard
    |-- cors
    |-- utils //(Helper function, shared function, db) There is a high probability.
    |-- db
    |-- config //Project configuration (environment variable processing), not necessarily.


  1. Other project structures

    There are other splitting methods for this splitting direction, possibly merging routes and controllers, which is also very common. In the above split method, there is no logic in routes, it just points to controllers.

    Another way to split is to add a layer of services. The logic of services is separated from controllers. If it is removed, controllers will not be responsible for logic processing. Each additional layer of the project becomes more complex.


Share