Complete NestJs Boilerplate 🔥 🚀
This repo will representative of authentication service and authorization service
Complete NestJs is a Http NestJs v9.x boilerplate. Best uses for backend service.
You can request feature or report bug with following this link
Table of contents
- Important
- Next Todo
- Build With
- Objective
- Features
- Structure
- Prerequisites
- Getting Started
- API Reference
- Environment
- Api Key Encryption
- Adjust Mongoose Setting
- License
- Contact
Important
- The features will replated with AWS Features
- If you want to implement
database transactions
, you must run MongoDB as areplication set
. - If you change the environment value of
APP_ENV
toproduction
, that will trigger.- CorsMiddleware will implement
src/configs/middleware.config.ts
. - Documentation will
disable
.
- CorsMiddleware will implement
Next Todo
Next development
- serialization update
- update unit test for common modules
- user e2e
- api key for saas, change
x-api-key
to${key}:${secret}
- user plan module
- invoicing plan module
- excel decorator optimize
- Authorization optimize, remove permission entity and implement policy guard
- Google SSO
- Background export/import from/to CSV and Excel
- Update Documentation, include an diagram for easier comprehension
Build with
Describes which version.
Name | Version |
---|---|
NestJs | v9.3.x |
NodeJs | v18.12.x |
Typescript | v5.0.x |
Mongoose | v7.0.x |
MongoDB | v6.0.x |
Yarn | v1.22.x |
NPM | v8.19.x |
Docker | v20.10.x |
Docker Compose | v2.6.x |
Swagger | v6.2.x |
Objective
- Easy to maintenance
- NestJs Habit
- Component based folder structure
- Stateless authentication and authorization
- Repository Design Pattern or Data Access Layer Design Pattern
- Follow Community Guide Line
- Follow The Twelve-Factor App
- Adopt SOLID and KISS principle
- Support Microservice Architecture, Serverless Architecture, Clean Architecture, and/or Hexagonal Architecture
Features
Main Features
- NestJs v9.x 🥳
- Typescript 🚀
- Production ready 🔥
- Repository Design Pattern (Multi Repository, can mix with
TypeORM
) - Swagger / OpenAPI 3 included
- Authentication (
Access Token
,Refresh Token
,API Key
, andGoogle SSO
) - Authorization, Role and Permission Management (
PermissionToken
) - Support multi-language
i18n
🗣, can controllable with request headerx-custom-lang
- Request validation for all request params, query, dan body with
class-validation
- Serialization with
class-transformer
- Url Versioning, default version is
1
- Server Side Pagination
- Import and export data with CSV or Excel by using
decorator
Database
- MongoDB integrate by using mongoose 🎉
- Multi Database
- Database Transaction
- Database Soft Delete
- Database Migration
Logger and Debugger
- Logger with
Morgan
- Debugger with
Winston
📝
Security
- Apply
helmet
,cors
, andrate-limit
- Timeout awareness and can override ⌛️
- User agent awareness, and can whitelist user agent
Setting
- Support environment file
- Centralize configuration 🤖
- Centralize response
- Centralize exception filter
- Setting from database 🗿
Third Party Integration
- Storage integration with
AwsS3
- Upload file
single
andmultipart
to AwsS3
Others
- Support Docker installation
- Support CI/CD with Github Action or Jenkins
- Husky GitHook for check source code, and run test before commit 🐶
- Linter with EsLint for Typescript
Structure
Folder Structure
/app
The final wrapper module/common
The common module/configs
The configurations for this project/health
health check module for every service integrated/jobs
cron job or schedule task/language
json languages/migration
migrate all init data/modules
other modules based on service based on project/router
endpoint router.Controller
will put in this
Module structure
Full structure of module
.
└── module1
├── abstracts
├── constants // constant like enum, static value, status code, etc
├── controllers // business logic for rest api
├── decorators // warper decorator, custom decorator, etc
├── dtos // request validation
├── docs // swagger / OpenAPI 3
├── errors // custom error
├── filters // custom filter
├── guards // validate related with database
├── indicators // custom health check indicator
├── interceptors // custom interceptors
├── interfaces
├── middleware
├── pipes
├── repository
├── entities // database entities
├── repositories // database repositories
└── module1.repository.module.ts
├── serializations // response serialization
├── services
├── tasks // task for cron job
└── module1.module.ts
Response Structure
This section will describe the structure of the response.
Response Default
Default response for the response
export class ResponseDefaultSerialization {
statusCode: number;
message: string;
_metadata?: IResponseMetadata;
data?: Record<string, any>;
}
Response Paging
Default response for pagination.
export class ResponsePagingSerialization {
statusCode: number;
message: string;
totalData: number;
totalPage?: number;
currentPage?: number;
perPage?: number;
_availableSearch?: string[];
_availableSort?: string[];
_metadata?: IResponseMetadata;
data: Record<string, any>[];
}
Response Metadata
This is useful when we need to give the frontend some information that is related / not related with the endpoint.
export interface IResponseMetadata {
languages: ENUM_MESSAGE_LANGUAGE[];
timestamp: number;
timezone: string;
requestId: string;
path: string;
version: string;
repoVersion: string;
nextPage?: string;
previousPage?: string;
firstPage?: string;
lastPage?: string;
[key: string]: any;
}
Prerequisites
We assume that everyone who comes here is programmer with intermediate knowledge
and we also need to understand more before we begin in order to reduce the knowledge gap.
- Understand NestJs Fundamental, Main Framework. NodeJs Framework with support fully TypeScript.
- UnderstandTypescript Fundamental, Programming Language. It will help us to write and read the code.
- Understand ExpressJs Fundamental, NodeJs Base Framework. It will help us in understanding how the NestJs Framework works.
- Understand what NoSql is and how it works as a database, especially MongoDB.
- Understand Repository Design Pattern or Data Access Object Design Pattern. It will help to read, and write the source code
- Understand The SOLID Principle and KISS Principle for better write the code.
- Optional. Understand Microservice Architecture, Clean Architecture, and/or Hexagonal Architecture. It can help to serve the project.
- Optional. Understanding The Twelve Factor Apps. It can help to serve the project.
- Optional. Understanding Docker. It can help to run the project.
Getting Started
Before start, we need to install some packages and tools. The recommended version is the LTS version for every tool and package.
Make sure to check that the tools have been installed successfully.
Clone Repo
Clone the project with git.
git clone https://github.com/fedi-dayeg/complete-nestjs-boilerplate.git
Install Dependencies
This project needs some dependencies. Let's go install it.
yarn install
Create environment
Make your own environment file with a copy of env.example
and adjust values to suit your own environment.
cp .env.example .env
To know the details, you can read the documentation. Jump to document section
Database Migration
The migration will do data seeding to MongoDB. Make sure to check the value of the
DATABASE_
prefix in your.env
file.
The Database migration used NestJs-Command
For seeding
yarn seed
For remove all data do
yarn rollback
Test
The test is still not good net. I'm still lazy too do that.
The project provide 3 automation testing unit testing
, integration testing
, and e2e testing
.
yarn test
For specific test do this
-
Unit testing
yarn test:unit
-
Integration testing
yarn test:integration
-
E2E testing
yarn test:e2e
Run Project
Finally, Cheers 🍻🍻 !!! you passed all steps.
Now you can run the project.
yarn start:dev
Run Project with Docker
For docker installation, we need more tools to be installed in our instance.
Then run
docker-compose up -d
API Reference
You can check The ApiSpec after running this project. here
Documentation
Ongoing update
Adjust Mongoose Setting
Optional, if your mongodb version is < 5
Go to file src/common/database/services/database.options.service.ts
and add useMongoClient
to mongooseOptions
then set value to true
.
const mongooseOptions: MongooseModuleOptions = {
uri,
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
useMongoClient: true // <--- add this
};
License
Distributed under MIT licensed.
Contribute
How to contribute in this repo
-
Fork the project with click
Fork
button of this repo. -
Clone the fork project
git clone "url you just copied"
-
Make necessary changes and commit those changes
-
Commit the changes
git commit -m "your message"
-
Push changes to fork project
git push origin -u main
-
Back to browser, goto your fork repo github. Then, click
Compare & pull request
If your code behind commit with the original, please update your code and resolve the conflict. Then, repeat from number 6.
Rule
- Avoid Circular Dependency
- Consume component folder structure, and repository design pattern
- Always make
service
for every module is independently. - Do not put
controller
into service modules, cause this will break the dependency. Only put the controller intorouter
and then inject the dependency. - Put the config in
/configs
folder, and for dynamic config put asenvironment variable
CommonModule
only for main package, and put the module that related of service/project into/src/modules
. So, if we want to clear the unnecessary module, we just need to delete thesrc/modules/**
- If there a new service in CommonModule. Make sure to create the unit test in
/test/unit
. - If there a new controller, make sure to create the e2e testing in
test/e2e