Giter VIP home page Giter VIP logo

test's Introduction

NestJS v9 Webpack Boilerplate

Banner

Language License Version

๐Ÿ”ฅ Features

  • ๐Ÿ† Graceful Production Deployment

  • ๐Ÿงญ Unified API Response Structure

  • โšก Extreme Performance Optimize

  • ๐Ÿ“ Fully Integrated Coding Quality Tools

โš ๏ธ Attention

Although there are advantages to using Webpack bundling your code (especially for serverless applications), there are some constraints, and details here (UPDATE: Both examples stated by the NestJS creator have already unblinded the native driver and are good to use now). Therefore, please make sure your application does not contain native bindings library, then you can enjoy the benefits.

Extra Configuration for Dependency Packages

You should install copy-webpack-plugin and copy bull default commands to the output directory when building the code.

pnpm install -D copy-webpack-plugin
// webpack.config.js;
const CopyWebpackPlugin = require('copy-webpack-plugin');
// ...
module.exports = {
  plugins: [
    // ...
    new CopyWebpackPlugin({
      patterns: [
        {
          context: 'node_modules/bull/lib/commands',
          from: '**/*.lua',
        },
      ],
    }),
  ];
}

๐Ÿ““ Commands

Commands Description

# build the app
$ pnpm build

# format the code
$ pnpm lint

# start the app
$ pnpm start

# run in development mode
$ pnpm start:dev || pnpm dev

# build the app and run it in production mode
$ pnpm start:prod || pnpm prod

# generate Swagger JSON schema
$ pnpm swagger

# test both unit test and e2e test
$ pnpm test

# test all the e2e test
$ pnpm test:e2e

# test all the unit test
$ pnpm test:unit

Running Application for Development

$ git clone <repo>

$ pnpm install

# Fill in require information in .env file
$ cp .env.example .env

# Linux / Mac users may require (allow git hook script executable)
$ chmod +x .husky -R

$ pnpm dev

๐Ÿ“ Boilerplate Structure

โ”œโ”€โ”€ ci
โ”‚   โ”œโ”€โ”€ docker-compose.yaml
โ”‚   โ””โ”€โ”€ Dockerfile
โ”œโ”€โ”€ .husky
โ”‚   โ”œโ”€โ”€ _
โ”‚   โ”‚   โ”œโ”€โ”€ .gitignore
โ”‚   โ”‚   โ””โ”€โ”€ husky.sh
โ”‚   โ”œโ”€โ”€ commit-msg
โ”‚   โ”œโ”€โ”€ pre-commit
โ”‚   โ””โ”€โ”€ pre-push
โ”œโ”€โ”€ src
โ”‚   โ”œโ”€โ”€ exception
โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ””โ”€โ”€ normal.exception.ts
โ”‚   โ”œโ”€โ”€ filter
โ”‚   โ”‚   โ”œโ”€โ”€ all-exception.filter.ts
โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ”œโ”€โ”€ normal-exception.filter.ts
โ”‚   โ”‚   โ””โ”€โ”€ validator-exception.filter.ts
โ”‚   โ”œโ”€โ”€ interceptor
โ”‚   โ”‚   โ””โ”€โ”€ response.interceptor.ts
โ”‚   โ”œโ”€โ”€ modules
โ”‚   โ”‚   โ”œโ”€โ”€ app
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ dto
โ”‚   โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ response
โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ version.dto.ts
โ”‚   โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ index.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ app.config.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ app.controller.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ app.module.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ app.service.spec.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ app.service.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ index.ts
โ”‚   โ”‚   โ””โ”€โ”€ http
โ”‚   โ”‚       โ”œโ”€โ”€ http.module.ts
โ”‚   โ”‚       โ””โ”€โ”€ http.service.ts
โ”‚   โ”œโ”€โ”€ shared
โ”‚   โ”‚   โ”œโ”€โ”€ enums
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ log-level.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ node-env.ts
โ”‚   โ”‚   โ”œโ”€โ”€ interfaces
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ index.ts
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ response.ts
โ”‚   โ”‚   โ””โ”€โ”€ constants.ts
โ”‚   โ”œโ”€โ”€ utils
โ”‚   โ”‚   โ”œโ”€โ”€ clustering.ts
โ”‚   โ”‚   โ”œโ”€โ”€ helper.ts
โ”‚   โ”‚   โ””โ”€โ”€ swagger.ts
โ”‚   โ”œโ”€โ”€ env.d.ts
โ”‚   โ””โ”€โ”€ main.ts
โ”œโ”€โ”€ test
โ”‚   โ”œโ”€โ”€ app.e2e-spec.ts
โ”‚   โ”œโ”€โ”€ common.ts
โ”‚   โ””โ”€โ”€ jest.e2e.config.ts
โ”œโ”€โ”€ .vscode
โ”‚   โ”œโ”€โ”€ extensions.json
โ”‚   โ””โ”€โ”€ settings.json
โ”œโ”€โ”€ .commitlintrc.js
โ”œโ”€โ”€ .dockerignore
โ”œโ”€โ”€ .editorconfig
โ”œโ”€โ”€ .env.example
โ”œโ”€โ”€ .eslintignore
โ”œโ”€โ”€ .eslintrc.js
โ”œโ”€โ”€ .gitattributes
โ”œโ”€โ”€ .gitignore
โ”œโ”€โ”€ jest.config.ts
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ .lintstagedrc.js
โ”œโ”€โ”€ nest-cli.json
โ”œโ”€โ”€ .npmrc
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ pnpm-lock.yaml
โ”œโ”€โ”€ .prettierrc.js
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ SECURITY.md
โ”œโ”€โ”€ tsconfig.json
โ””โ”€โ”€ webpack.config.js

โญ Coding Quality Tools Details Description

ESLint

It statically analyzes your code to help you detect formatting issues and find code inconsistencies, here we extend the ESLint TypeScript recommend rules, the most popular JavaScript style Airbnb, auto import sorting and shaking plugins.

# Config File
โ”œโ”€โ”€ .eslintignore
โ””โ”€โ”€ .eslintrc.js

Prettier

Similar to ESLint, but mainly focus on auto-formatting, not the code quality. Actually, ESLint can do all the jobs that Prettier can do, but for the formatting part, Prettier does better, so we import both and achieve each of the advantages. About the conflict of the formatting part, we can import plugin:prettier/recommended to solve this, but keep in mind that this plugin should extend at the last.

# Config File
โ””โ”€โ”€ .prettierrc.js

Editorconfig

It defines a standard code formatting style guide among all the IDEs and editors used within a team of developers. Basically, all the rules in the Editorconfig should sync with Prettier, Editorconfig focus on newly created files, ESLint and Prettier focus on existing files.

# Config File
โ””โ”€โ”€ .editorconfig

Husky + Commitlint + Lint-staged

These tools are the wrapper of Git Hook. Lint-staged enforces you to format your code (run pnpm lint) before committing, but the tools will cache the file that is already formatted to improve performance. Commitlint enforces your commit message to fit a specific format, here we extend Conventional Commits (officially recommend setting).

# Type: build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test
# Commitlint Format:

<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
# Config File for Lint-staged
โ””โ”€โ”€ .lintstagedrc.js

# Config File for Commitlint
โ””โ”€โ”€ .commitlintrc.js

# Config File for Husky
โ”œโ”€โ”€ .husky
|   โ”œโ”€โ”€ commit-msg  # call Commitlint to check the commit message
|   โ”œโ”€โ”€ pre-commit  # call Eslint to lint the coding issue
|   โ””โ”€โ”€ pre-push    # call Jest to do the unit + e2e test

Git Attributes

To synchronize the end-of-line of the git repository.

# Config File
โ””โ”€โ”€ .gitattributes

โš™๏ธ Other Configuration

Pnpm

We use preinstall script forcing Pnpm as default package manager because it is a fast and disk space efficient manager compare with Npm and Yarn.

Webpack

We overwrite the default webpack.config.js so that the production build can bundle all required libraries in main.ts. For the configuration, we ignored a list of the nestjs-buildin library so that we could build it without error. If you need these libraries for your development, you can comment it in the lazy imports list.

Alias Path

Using an alias path can prevent dirty relative paths (e.g. ../../../), also it is easier to import files in the deep directory (e.g. src/assets/img/testing/...).

# Config File
โ””โ”€โ”€ tsconfig.json

API Response

Success Response

{
  "data": {
    "...": "..."
  }
}

Error Response

{
  "error": {
    "code": 400,
    "message": "..."
  }
}

We use Google JSON guide to be the response format implemented by filtering + interceptor, which is the built-in feature of NestJS, to sync with the response format. All exceptions will be caught by filtering, and all normal returns will be transformed by the interceptor.

# Related Directory
โ”œโ”€โ”€ src
|   โ”œโ”€โ”€ exception
|   โ”œโ”€โ”€ filter
|   โ””โ”€โ”€ interceptor

Environment Variables Validation

We use Joi library for the validation, which is recommended by NestJS.

# Config File
โ”œโ”€โ”€ src
|   โ””โ”€โ”€ app.config.ts

HTTP Request

Since @nestjs/axios default return Observable, it does not fit the common use case (Promise based), so we use a custom module to implement secondary encapsulation of the native Axios library, also extract .data from the response to prevent .data.data.data... chaining.

Reference:

Pino Logger

We used nestjs-pino to auto-log every request metadata and response time. We also centralized Pino config in app.config.ts for main.ts to reuse it.

Swagger

@nestjs/swagger allows you to auto-generate the API document, but here we decouple the document and the service. You can run pnpm swagger to generate the schema and put it into Swagger UI to host your API document as a static page. We have two examples in app.controller.ts to show you how to integrate the Google JSON response format. We also have a GitHub Action example to auto-update the schema and host it to the GitHub Pages. If you do not want this setup, you can just follow NestJS official guideline to host your document inside the service.

Attention: You do not need to wrap the data object to your DTO for every response, you only have to name your DTO end with 'Res', swagger.ts script will auto-wrap for you and display correctly in the Swagger UI.

Swagger UI Final Output

Docker Containerization

We also set up the Dockerfile with multi-stage builds to optimize your image size and building time. For the docker-compose config, we also included health checking.

# Config File
โ”œโ”€โ”€ ci
|   โ”œโ”€โ”€ docker-compose.yaml
|   โ””โ”€โ”€ Dockerfile

Clustering

We also configured the clustering feature for the service to improve performance. All you need to do is just config the environment variable CLUSTERING=true.

โ˜‘๏ธ Naming Convention

JS variable / function: lower camel case [e.g. twoWords]

JS global const + enum's attributes: upper case [e.g. TWO_WORDS]

JS class / interface / type / enum: pascal case [e.g. TwoWords]

Asset name (e.g. image): kebab case [e.g. two-words]

๐Ÿ“ˆ Performance Optimization

By default, we used Fastify instead of Express to achieve twice of performance, below are the benchmarks tested by NestJS:

Express.js

Stat 1% 2.5% 50% 97.5% Avg Stdev Min
Req/Sec 14183 14183 15767 15991 15640 501.13 14182
Bytes/Sec 3.06 MB 3.06 MB 3.41 MB 3.45 MB 3.38 MB 108 kB 3.06 MB

Fastify

Stat 1% 2.5% 50% 97.5% Avg Stdev Min
Req/Sec 19935 19935 33247 34111 32030.4 4103.84 19931
Bytes/Sec 3.03 MB 3.03 MB 5.05 MB 5.19 MB 4.87 MB 624 kB 3.03 MB

Reference:

License

This project is licensed under the MIT License, Copyright ยฉ 2022. See LICENSE for more information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.