Http NestJs v9.x Boilerplate.
You can Request Feature or Report Bug with following this link
- Important
- Next Todo
- Build With
- Objective
- Features
- Prerequisites
- Getting Started
- API Reference
- Environment
- Api Key Encryption
- Adjust Mongoose Setting
- License
- Contact
If you change env value of APP_ENV
to production
that will trigger
- CorsMiddleware will implement
src/configs/middleware.config.ts
, else default is*
. - Documentation will
disable
Next development
- Implement Repository Design Pattern / Data Access Object Design Pattern
- Swagger for API Documentation
- Support Serverless
- Mongo Repository soft delete
- Make it simple
- Encrypt jwt payload
- Optimize Unit Testing
- Optimize Swagger (Ongoing)
- Add Relational Database Repository, ex: mysql, postgres (Ongoing)
- Update Documentation, include an diagram for easier comprehension
- Export to excel and Import from excel add options to background process
- OAuth2 Client Credentials
- AuthApi Controller
- Maybe will adopt CQRS
Describes which version .
Name | Version |
---|---|
NestJs | v9.x |
NodeJs | v18.x |
Typescript | v4.x |
Mongoose | v6.x |
MongoDB | v6.x |
PostgreSQL | - |
Yarn | v1.x |
NPM | v8.x |
Docker | v20.x |
Docker Compose | v2.x |
Swagger | v6.x |
Aws CLI | v2.x |
- Easy to maintenance
- NestJs Habit
- Component based folder structure
- Repository Design Pattern or Data Access Layer Design Pattern
- Support Microservice Architecture, Clean Architecture, and/or Hexagonal Architecture
- Follow The Twelve-Factor App
- Adopt SOLID and KISS principle
- NestJs v9.x 🥳
- Typescript 🚀
- Production ready 🔥
- Support serverless
- Swagger included
- Authentication and authorization (
JWT
,API Key
) 💪 - Role management system
- Storage integration with
AwsS3
- Upload file
single
andmultipart
to AwsS3 - Support multi-language
i18n
🗣 - Request validation with
class-validation
- Serialization with
class-transformer
- Url Versioning
- Server Side Pagination, there have 3 of types
- Import and export data with excel by using
decorator
- MongoDB integrate by using
mongoose
🎉 - PostgreSQL integrate by using
typeorm
🎊 (Ongoing) - Multi Database
- Database Transaction
- Database Soft Delete
- Database Migration
- Logger
Morgan
and DebuggerWinston
📝
- Apply
helmet
,cors
, andrate-limit
- Timeout awareness and can override ⌛️
- User agent awareness, and can whitelist user agent
- Support environment file
- Centralize configuration 🤖
- Centralize response
- Centralize exception filter
- Setting from database 🗿
- Maintenance mode on / off from database 🐤
- 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
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 us to read 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.
- Optional. Understand The Twelve Factor Apps
- Optional. Understand Docker that can help you to run the project
Before we start, we need to install some packages and tools. Recommend version is LTS Version for every tool and package.
Make sure check that tools has been installed successfully.
Clone ack-nestjs-boilerplate with git.
git clone https://github.com/andrechristikan/ack-nestjs-boilerplate.git
This project need some dependencies. Let's go install it.
yarn install
Make your own environment with copy from .env.example
and edit some value.
cp .env.example .env
If you want to to implement
transaction
, you must to installMongodb Replication Set
.
Database migration ack-nestjs-boilerplate used NestJs-Command
For migrate
yarn migrate
For rollback
yarn rollback
ack-nestjs-boilerplate provide 3 automation testing unit testing
, integration testing
, and e2e testing
.
yarn test
For specific test use this
-
Unit testing
yarn test:unit
-
Integration testing
yarn test:integration
-
E2E testing
yarn test:e2e
If mongodb version < 5, Read this section for adjust mongoose setting.
Finally, Cheers 🍻🍻 !!! we passed all steps.
Now we can run ack-nestjs-boilerplate and use all of features.
yarn start:dev
docker-compose up -d
We have already provided the API reference. To visit, click here.
Detail information about the environment
Key | Type | Description |
---|---|---|
APP_NAME | string |
Application name and will be subject for jwt |
APP_ENV | string |
|
APP_LANGUAGE | string |
Enum languages, separator , |
Key | Type | Description |
---|---|---|
HTTP_HTTP_ENABLE | boolean |
Application Http on/off |
HTTP_HOST | string |
Application host serve |
HTTP_PORT | number |
Application port serve |
HTTP_VERSIONING_ENABLE | boolean |
Application url versioning on/off |
HTTP_VERSION | number |
Application version number |
Key | Type | Description |
---|---|---|
DEBUGGER_HTTP_WRITE_INTO_FILE | boolean |
Http debugger write into file |
DEBUGGER_SYSTEM_WRITE_INTO_FILE | boolean |
System debugger write into file |
Key | Type | Description |
---|---|---|
MIDDLEWARE_TIMESTAMP_TOLERANCE | string |
Tolerance timestamp ApiKey . ms package value |
MIDDLEWARE_TIMEOUT | string |
Request timeout. ms package value |
Key | Type | Description |
---|---|---|
DOC_NAME | string |
Documentation tittle |
DOC_VERSION | number |
Documentation version |
Key | Type | Description |
---|---|---|
JOB_ENABLE | boolean |
Application Job turn on/off |
Key | Type | Description |
---|---|---|
DATABASE_HOST | string |
Mongodb URL. Support standard url , replication , or srv |
DATABASE_NAME | string |
Database name |
DATABASE_USER | string |
Database user |
DATABASE_PASSWORD | string |
Database user password |
DATABASE_DEBUG | boolean |
Trigger database DEBUG |
DATABASE_OPTIONS | string |
Mongodb connect options |
Key | Type | Description |
---|---|---|
AUTH_JWT_SUBJECT | setting |
Jwt subject |
AUTH_JWT_AUDIENCE | string |
Jwt audience |
AUTH_JWT_ISSUER | string |
JWT issuer |
AUTH_JWT_ACCESS_TOKEN_SECRET_KEY | string |
Secret access token, free text. |
AUTH_JWT_ACCESS_TOKEN_EXPIRED | string |
Expiration time for access token. ms package value |
AUTH_JWT_ACCESS_TOKEN_ENCRYPT_KEY | string |
Encrypt key for access token payload |
AUTH_JWT_ACCESS_TOKEN_ENCRYPT_IV | string |
Encrypt IV for access token payload |
AUTH_JWT_REFRESH_TOKEN_SECRET_KEY | string |
Secret refresh token, free text. |
AUTH_JWT_REFRESH_TOKEN_EXPIRED | string |
Expiration time for refresh token. ms package value |
AUTH_JWT_REFRESH_TOKEN_REMEMBER_ME_EXPIRED | string |
Expiration time for refresh token when remember me is checked. ms package value |
AUTH_JWT_REFRESH_TOKEN_NOT_BEFORE_EXPIRATION | string |
Token active for refresh token before x time. ms package value |
AUTH_JWT_REFRESH_TOKEN_ENCRYPT_KEY | string |
Encrypt key for refresh token payload |
AUTH_JWT_REFRESH_TOKEN_ENCRYPT_IV | string |
Encrypt IV for refresh token payload |
Key | Type | Description |
---|---|---|
SERVERLESS_AWS_API_GATEWAY | string |
AWS api gateway for server the aws lamda |
SERVERLESS_AWS_PROFILE | string |
AWS profile for deployment |
SERVERLESS_AWS_S3_BUCKET | string |
AWS s3 bucket for save the development asset |
Key | Type | Description |
---|---|---|
AWS_CREDENTIAL_KEY | string |
AWS account credential key |
AWS_CREDENTIAL_SECRET | string |
AWS account credential secret |
AWS_S3_REGION | string |
AWS S3 Region |
AWS_S3_BUCKET | string |
AWS S3 Name of Bucket |
ApiKeyHashed using
sha256
encryption, and then encryption fordataObject
isAES256
. Please keep thesecret
keep private.
To do the encryption
-
Concat the
key
andsecret
.const apiKeyString = `${key}:${secret}`;
-
Encryption
apiKeyString
with sha256const apiKeyHashed = this.helperHashService.sha256(`${key}:${secret}`); // e11a023bc0ccf713cb50de9baa5140e59d3d4c52ec8952d9ca60326e040eda54
-
Then put the
apiKeyHashed
intodataObject
const timestamp = this.helperDateService.timestamp(); const data: IAuthApiRequestHashedData = { key: "qwertyuiop12345zxcvbnmkjh", timestamp, hash: apiKeyHashed, }
-
Encryption the
dataObject
withAES 256
These data
encryptionKey
, andpassphrase
can be find in database.const passphrase = 'cuwakimacojulawu'; // <--- IV for encrypt AES 256 const encryptionKey = 'opbUwdiS1FBsrDUoPgZdx'; const apiKeyEncryption = await authApiService.encryptApiKey( data, encryptionKey, passphrase );
-
Last, combine the
key
andapiKeyEncryption
const xApiKey = `${key}:${apiEncryption}`;
-
Send into request. Put the
xApiKey
in request headers{ "headers": { "x-api-key": "${xApiKey}", ... ... ... } }
Just is case, if your mongodb version is < 5
Go to file src/common/database/services/database.options.service.ts
and remove comment useMongoClient
then set value to true
.
const mongooseOptions: MongooseModuleOptions = {
uri,
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
useMongoClient: true
};
Distributed under MIT licensed.