Introducing some best practices at the beginning of a project can avoid a lot of complex refactoring later on. This article summarizes some best practices for building Web services using Node JS, as well as the specific steps involved.

Use the initialization scaffolding

Scaffolding helps automatically generate some code and project structure and inject some framework when initializing the code base. For a NodeJS project, there is no need to install dependencies step by step, starting with NPM init initialization.

Express command

Express is currently the most popular NodeJS Web framework. Globally install an Express-Generator to initialize the Express project.

  • Global installation commands:
    npm 
                                                        install express-generator -gCopy the code
  • Create a new one calledhello-expressProject:
    express 
                                                        hello-expressCopy the code

    Initialize the Express project using scaffolding

Use Swagger scaffolding

When developing Web apis using NodeJS, it is highly recommended to use Swagger for API building and management, as well as providing API documentation services. The global Install Swagger command also initializes a Swagger project. The Swagger command lets you edit your API definitions and debug apis directly in real time on your browser.

Initialize the Swagger project

  • Installation command:
    npm 
                                                        install swagger -gCopy the code
  • New Swagger API Project:
    swagger 
                                                        project create hello-swaggerCopy the code

    In the process, you are asked to choose which Web server to use, and the Express framework is automatically introduced when you select Express

  • Project Structure:
. ├ ─ ─ the README. Md ├ ─ ─ API │ ├ ─ ─ controllers │ │ ├ ─ ─ the README. Md │ │ └ ─ ─ the hello_world. Js │ ├ ─ ─ helpers │ │ └ ─ ─ the README. Md │ ├ ─ ─ │ ├─ ├─ ├─ ├─ ├─ bass exercises ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt ├─ download.txt  README.mdCopy the code

 

Real-time editing and syntax verification

  • Start online editing:
    swagger 
                                                        project editCopy the code

    At this time, the system browser will be opened, in which swagger document can be directly edited and real-time grammar check can be carried out. Meanwhile, the editing changes in the browser will be written back to the code.

Online debugging API

On the right hand side of the diagram, it looks something like

postman

                                                Copy the code

Swagger document service

Swagger is one of the most popular API building and management tools. It is supported by libraries in various languages and frameworks, while installing Swagger UI extension for API document management and online debugging. It follows the OpenAPI standard, which defines a set of API specifications such as routing and forwarding, parameter definition and verification, etc.

  • OpenAPI specifications document swagger. IO /specificati…
  • Online API editor preview: editor.swagger. IO

Publish swagger documentation

The swagger command above is suitable for local editing, debugging, and introduction of Swagger UI middleware when publishing document services in a Production environment

<
                                                span class="hljs-selector-tag">app<
                                                    /span><span class=
                                                        "hljs-selector-class">.use</
                                                            span>(<span class=
                                                                "hljs-selector-tag">SwaggerUi</span
                                                                    >(<span class=
                                                                        "hljs-selector-tag">swaggerExpress</span
                                                                            ><span class="hljs-selector-class"
                                                                                >.runner</span
                                                                                    ><span class="hljs-selector-class"
                                                                                        >.swagger</span
                                                                                            >));

                                                                                                Copy the code

Visit http://localhost:10010/docs/#/ to view the API documentation:

  • Online preview: petStore.swagger. IO /
  • The complete code is as follows:
SwaggerExpress.create(config, function (err, swaggerExpress) { if (err) { throw err; } // install middleware app.use(SwaggerUi(swaggerExpress.runner.swagger)); swaggerExpress.register(app); const port = 10010; app.listen(port); If (swaggerExpress. Runner. Swagger. Paths ['/hello ']) {the console. The log (' try this: \ ncurl http://127.0.0.1: '+ + port '/hello?name=Scott'); }});Copy the code

 

Enable ES6 JS syntax

ECMAScript is the JS language standard, and ES6 is the new JS syntax standard. An error occurs when using ES6 syntax with no other configuration. We need to introduce Babel for syntactic transformations.

import SwaggerExpress from 'swagger-express-mw'; ^^^^^^^^^^^^^^ SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:760:23) at Object.Module._extensions.. js (internal/modules/cjs/loader.js:827:10)Copy the code

What is the Babel

Babel is a JavaScript compiler, toolchain, primarily used to convert ECMAScript 2015+ version code into backs-compatible JavaScript syntax so that it can run in current and older versions of browsers or other environments. More documentation is available at www.babeljs.cn/docs/

How to configure it?

  • Install dependencies:
npm install -D @babel/core @babel/cli @babel/preset-env @babel/nodeCopy the code

 

  • Create a. Babelrc file in the root directory with the following contents
{ 
  "presets": ["@babel/preset-env"] 
}Copy the code

  • Use the babel-node command instead of node
"scripts": {
    "start": "npm run prod",
    "server": "node ./app.js"  // -> "babel-node ./app.js"
}Copy the code

 

How do I handle existing non-ES6 projects?

  • Install an NPM module
    cjs
                                                        -to-es6Copy the code

    You can do some simple ES6 syntax conversions:

    npm 
                                                            install -g cjs-
                                                                to-es6Copy the code

The resources

  • www.babeljs.cn/docs/
  • How to enable ES6 (and beyond) syntax with Node and Express:medium.freecodecamp.org/how-to-enab…

File changes monitor and automatically restart the service

We need to restart Express every time we change the code to see the effect,

nodemon

                                                Copy the code

  • Install nodemon:
    npm
                                                         i -D nodemonCopy the code
  • Add the nodemon.json configuration file to the root directory:
{
  "exec": "npm run dev",
  "watch": ["src/*", "public/*"],
  "ext": "js, html, css, json"
}Copy the code

 

  • Reference documents for more configurations: github.com/remy/nodemo…

5. Use ES Lint for code style scanning

ES Lint is a code style scanning tool, especially for team development, that helps us standardize our code style and provides integration with the IDE for code correction.

  • Install eslint
    npm
                                                         i -D eslintCopy the code
  • Reference documents: eslint.org/docs/user-g…

Trigger the specified action when the code is submitted

There are often scenarios where continuous integration requires that we test locally before committing code. At this point we can register the “hooks” and run the tests locally before committing the code, and if the tests fail, they are not allowed to commit. Then using

husky

                                                Copy the code

  • Husky Documentation: github.com/typicode/hu…

Example 1: Run tests before Git push