Initial commit

This commit is contained in:
free-land 2022-07-25 10:12:30 +00:00
commit 0fd6e72c8e
73 changed files with 18040 additions and 0 deletions

31
.dockerignore Normal file
View File

@ -0,0 +1,31 @@
#husky
# Build dependencies
node_modules/
coverage/
e2e-coverage/
integration-coverage/
dist/
.husky/
.github/
prod/
# Logs
logs/
# Environment (contains sensitive data)
.env*
# Versioning and metadata
.git
.gitignore
.dockerignore
.eslintignore
# Files not required for production
.editorconfig
dockerfile
docker-compose.yml
cspell.json
README.md
nodemon.json

6
.env.develop Normal file
View File

@ -0,0 +1,6 @@
NODE_ENV=development
NODE_PORT=8085
LOCAL_PORT=8085
IMAGE_VERSION=0.0.1
IMAGE_NAME="image-name"
CONTAINER_NAME="container-name"

6
.env.prod Normal file
View File

@ -0,0 +1,6 @@
NODE_ENV=production
NODE_PORT=8085
LOCAL_PORT=8085
IMAGE_VERSION=0.0.1
IMAGE_NAME="image-name"
CONTAINER_NAME="container-name"

6
.env.staging Normal file
View File

@ -0,0 +1,6 @@
NODE_ENV=development
NODE_PORT=8085
LOCAL_PORT=8085
IMAGE_VERSION=0.0.1
IMAGE_NAME="image-name"
CONTAINER_NAME="container-name"

9
.eslintignore Normal file
View File

@ -0,0 +1,9 @@
# /node_modules/* in the project root is ignored by default
# build artefacts
dist/*
coverage/*
node_modules/*
logs/*
prod/*
.husky/*
.git/*

28
.eslintrc.js Normal file
View File

@ -0,0 +1,28 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir : __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
"prettier"
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

104
.gitignore vendored Normal file
View File

@ -0,0 +1,104 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port

51
.gitignore copy Normal file
View File

@ -0,0 +1,51 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/e2e-coverage
/integration-coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# yarn
.yarn/*
.pnp.*
!.yarn/cache
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
# environment
.env
config.yaml
config.yml

0
.gitkeep Normal file
View File

1
.nvmrc Normal file
View File

@ -0,0 +1 @@
lts/fermium

5
.prettierrc Normal file
View File

@ -0,0 +1,5 @@
{
"singleQuote": true,
"trailingComma": "es5",
"tabWidth": 4
}

57
Dockerfile Normal file
View File

@ -0,0 +1,57 @@
FROM node:fermium-alpine AS environment
ARG MS_HOME=/app
ENV MS_HOME="${MS_HOME}"
ENV MS_SCRIPTS="${MS_HOME}/scripts"
ENV USER_NAME=node USER_UID=1000 GROUP_NAME=node GROUP_UID=1000
WORKDIR "${MS_HOME}"
# Build
FROM environment AS develop
COPY ["./package.json", "./package-lock.json", "${MS_HOME}/"]
FROM develop AS builder
COPY . "${MS_HOME}"
RUN PATH="$(npm bin)":${PATH} \
&& npm ci \
&& npm run test:ci \
&& npm run test:e2e \
&& npm run-script build \
# Clean up dependencies for production image
&& npm install --frozen-lockfile --production && npm cache clean --force
# Serve
FROM environment AS prod
COPY ["./scripts/docker-entrypoint.sh", "/usr/local/bin/entrypoint"]
COPY ["./scripts/bootstrap.sh", "/usr/local/bin/bootstrap"]
COPY --from=builder "${MS_HOME}/node_modules" "${MS_HOME}/node_modules"
COPY --from=builder "${MS_HOME}/dist" "${MS_HOME}/dist"
RUN \
apk --update add --no-cache tini bash \
&& deluser --remove-home node \
&& addgroup -g ${GROUP_UID} -S ${GROUP_NAME} \
&& adduser -D -S -s /sbin/nologin -u ${USER_UID} -G ${GROUP_NAME} "${USER_NAME}" \
&& chown -R "${USER_NAME}:${GROUP_NAME}" "${MS_HOME}/" \
&& chmod a+x \
"/usr/local/bin/entrypoint" \
"/usr/local/bin/bootstrap" \
&& rm -rf \
"/usr/local/lib/node_modules" \
"/usr/local/bin/npm" \
"/usr/local/bin/docker-entrypoint.sh"
USER "${USER_NAME}"
EXPOSE 8085
ENTRYPOINT [ "/sbin/tini", "--", "/usr/local/bin/entrypoint" ]

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

165
README.md Normal file
View File

@ -0,0 +1,165 @@
# Hexagonal architecture
# Table of Contents
- [Overview](#overview)
- [Code architecture](#code-architecture)
- [source code](#source-code)
- [Service build information](#service-build-information)
- [Regular user](#regular-user)
- [Advanced user](#advanced-user)
- [Deployment](#deployment)
- [Helm](#helm)
- [Kubernetes manifests](#kubernetes-manifests)
- [Monitoring and alerting](#monitoring-and-alerting)
- [Health check](#health-check)
- [OpenApi](#openapi)
- [Documentation](#documentation)
- [ToDo list](#todo-list)
## Overview
The **hexagonal architecture**, or **ports and adapters architecture**, is an architectural pattern used in [software design](https://en.wikipedia.org/wiki/Software_design "Software design"). It aims at creating [loosely coupled](https://en.wikipedia.org/wiki/Loose_coupling "Loose coupling") application components that can be easily connected to their software environment by means of ports and [adapters](https://en.wikipedia.org/wiki/Adapter_pattern "Adapter pattern"). This makes components exchangeable at any level and facilitates test automation.
---
## Code architecture
![Group 4 1svg](/images/structure.svg)
---
## source code
```bash
git clone https://github.com/MoeidHeidari/nestjs-boilerplate
cd monetary-transaction
```
## Service build information
There are different stages of building the application for this service. Based on the environment you want to deploy we have different ways to build the application. following information may help with building the service.
### Regular user
```bash
npm install
npm run build
npm run test:ci
npm start:{dev || debug || prod}
```
### Advanced user
```bash
cd scripts
bash run.sh -h
2022.05.30.14.43
Usage: $(basename "${BASH_SOURCE[0]}") [-h] [-buildDocker] [-runDocker] [-runApp] [-runDoc] [-packageHelm]
This script helps you to run the application in different forms. below you can get the full list of available options.
Available options:
-h, --help Print this help and exit
-buildDocker Build the docker image called "imageName:latest"
-runDocker Build the docker image and run on local machine
-runApp Run application with npm in usual way for development
-runDoc Generate the code documentation
-packageHelm makes a helm package from the helm chart.
```
## Deployment
#### Helm
with the following instruction you can install the helm chart on an up and running kubernetes cluster.
```bash
cd k8s
helm install {sample-app} {app-0.1.0.tgz} --set service.type=NodePort
```
#### Kubernetes manifests
Alternativelly you can deploy the application on an up an running kubernetes cluster using provided config files.
```bash
cd k8s/configFiles
kubectl apply -f app-namespace.yaml, app-configmap.yaml, app-deployment.yaml, app-service.yaml
```
it should give you following output
```bash
namespace/app created
configmap/app-config created
deployment.apps/app created
service/app created
```
## Monitoring and alerting
### Health check
by calling the following endpoint you can make sure that the application is running and listening to your desired port
`http://localhost:{port_number}/health`
most probably you will get a result back as follow
> **Example**
> {"status":"ok","info":{"alive":{"status":"up"}},"error":{},"details":{"alive":{"status":"up"}}}
mertics
to get the default metrics of the application you can use the following endpoint
`http://localhost:{port_number}/metrics`
## OpenApi
by calling the following endpoint you can see the Swagger OpenApi documentation and explore all the available apis and schemas.
`http://localhost:{port_number}/api`
## Documentation
By running following comman you can generate the full code documentation (Compodoc) and get access to it through port `7000`
```bash
npm run doc
```
http://localhost:7000
## ToDo list
- [ ] add terraform infrastructure

19
cspell.json Normal file
View File

@ -0,0 +1,19 @@
{
"words": [
"nestjs",
"metatype",
"virtuals",
"prebuild",
"Logform",
"transfomer",
"Insync",
"acks",
"microservices",
"globby",
"dockerhub",
"fifsky",
"buildx",
"baibay",
"exceljs"
]
}

15
docker-compose.yaml Normal file
View File

@ -0,0 +1,15 @@
version: '3.3'
services:
grover:
image: ${IMAGE_NAME}:${IMAGE_VERSION}
build:
context: .
dockerfile: Dockerfile
container_name: ${CONTAINER_NAME}
restart: always
ports:
- ${LOCAL_PORT}:${NODE_PORT}
environment:
- NODE_ENV= ${NODE_ENV}
- NODE_PORT= ${NODE_PORT}

573
images/structure.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 2.4 MiB

0
k8s/.gitkeep Normal file
View File

5
nest-cli.json Normal file
View File

@ -0,0 +1,5 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src"
}

5
nodemon.json Normal file
View File

@ -0,0 +1,5 @@
{
"watch": ["src"],
"ext": "ts",
"exec": "ts-node src/main"
}

15763
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

89
package.json Normal file
View File

@ -0,0 +1,89 @@
{
"name": "hometask",
"version": "0.0.1",
"description": "This is a boilerplate for Nodejs (Nestjs/typescript) that can be used to make http server application.",
"author": "Moeid Heidari",
"private": true,
"license": "Apache",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:ci": "jest --ci --detectOpenHandles --forceExit",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs-addons/in-memory-db": "^ 3.0.3",
"@nestjs/axios": "0.0.8",
"@nestjs/common": "^8.0.0",
"@nestjs/config": "^2.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/swagger": "^5.0.8",
"@nestjs/terminus": "^8.0.6",
"@willsoto/nestjs-prometheus": "^4.6.0",
"async-mutex": "^0.3.2",
"cache-manager": "^3.6.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"dotenv-expand": "^5.1.0",
"dotenv-flow": "^3.2.0",
"faker": "^5.1.0",
"prom-client": "^14.0.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.5"
},
"devDependencies": {
"@nestjs/cli": "^8.0.0",
"@nestjs/schematics": "^8.0.0",
"@nestjs/testing": "^8.0.0",
"@types/dotenv-flow": "^3.2.0",
"@types/express": "^4.17.13",
"@types/jest": "27.5.1",
"@types/node": "^17.0.38",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.0",
"morgan": "^1.10.0",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"swagger-ui-express": "^4.4.0",
"ts-jest": "28.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.0.0",
"typescript": "^4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

0
scripts/runner.go Normal file
View File

View File

@ -0,0 +1,24 @@
import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';
/**
* Health controller class
*/
@Controller('health')
export class HealthController {
/**
* Health check controller class constructor.
* @param health health check service
* @param http http response
*/
constructor(private health: HealthCheckService, private http: HttpHealthIndicator) {}
//======================================================================================================
/**
* Checks the liveness of the project
* @returns http response
*/
@Get()
@HealthCheck()
check() {
return { status: 'ok', info: { alive: { status: 'up' } }, error: {}, details: { alive: { status: 'up' } } };
}
}

View File

@ -0,0 +1 @@
export * from './health.controller'

1
src/application/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './controller'

View File

@ -0,0 +1,2 @@
export * from './roles.decorator';
export * from './public.decorator';

View File

@ -0,0 +1,10 @@
import { SetMetadata } from '@nestjs/common';
/**
* key for public state
*/
export const IS_PUBLIC_KEY = 'isPublic';
/**
* decorates method as public
*/
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);

View File

@ -0,0 +1,13 @@
import { SetMetadata } from '@nestjs/common';
import { Roles as Role } from '../domain/enums';
/**
* keys of roles
*/
export const ROLES_KEY = 'roles';
/**
* retuns a list of defined roles
* @param roles all the possible roles inside the enum
* @returns the list of roles
*/
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);

View File

View File

View File

@ -0,0 +1,56 @@
export enum HttpResponseDescriptions {
CONTINUE = 'The client SHOULD continue with its request',
SWITCHING_PROTOCOLS = "The server understands and is willing to comply with the client's request, via the Upgrade message header field, for a change in the application protocol being used on this connection",
PROCESSING = 'The 102 (Processing) status code is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it',
OK = 'The request has succeeded',
CREATED = 'The request has been fulfilled and resulted in a new resource being created',
ACCEPTED = 'The request has been accepted for processing, but the processing has not been completed',
NON_AUTHORITATIVE_INFORMATION = 'The returned metainformation in the entity-header is not the definitive set as available from the origin server, but is gathered from a local or a third-party copy',
NO_CONTENT = 'The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation',
RESET_CONTENT = 'The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent',
PARTIAL_CONTENT = 'The server has fulfilled the partial GET request for the resource',
AMBIGUOUS = 'The requested resource corresponds to any one of a set of representations, each with its own specific location, and agent- driven negotiation information (section 12) is being provided so that the user (or user agent) can select a preferred representation and redirect its request to that location',
MOVED_PERMANENTLY = 'The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs',
FOUND = 'The requested resource resides temporarily under a different URI',
SEE_OTHER = 'The response to the request can be found under a different URI and SHOULD be retrieved using a GET method on that resource',
NOT_MODIFIED = 'If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code',
TEMPORARY_REDIRECT = 'The requested resource resides temporarily under a different URI',
PERMANENT_REDIRECT = 'The request, and all future requests should be repeated using another URI',
BAD_REQUEST = 'The request could not be understood by the server due to malformed syntax',
UNAUTHORIZED = 'The request requires user authentication',
PAYMENT_REQUIRED = 'This code is reserved for future use.',
FORBIDDEN = 'The server understood the request, but is refusing to fulfill it',
NOT_FOUND = 'The server has not found anything matching the Request-URI',
METHOD_NOT_ALLOWED = 'The method specified in the Request-Line is not allowed for the resource identified by the Request-URI',
NOT_ACCEPTABLE = 'The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request',
PROXY_AUTHENTICATION_REQUIRED = 'This code is similar to 401 (Unauthorized), but indicates that the client must first authenticate itself with the proxy',
REQUEST_TIMEOUT = 'The client did not produce a request within the time that the server was prepared to wait',
CONFLICT = 'The request could not be completed due to a conflict with the current state of the resource',
GONE = 'The requested resource is no longer available at the server and no forwarding address is known',
LENGTH_REQUIRED = 'The server refuses to accept the request without a defined Content- Length',
PRECONDITION_FAILED = 'The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server',
PAYLOAD_TOO_LARGE = 'The server is refusing to process a request because the request entity is larger than the server is willing or able to process',
URI_TOO_LONG = 'The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret',
UNSUPPORTED_MEDIA_TYPE = 'The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method',
REQUESTED_RANGE_NOT_SATISFIABLE = 'A server SHOULD return a response with this status code if a request included a Range request-header field (section 14.35), and none of the range-specifier values in this field overlap the current extent of the selected resource, and the request did not include an If-Range request-header field',
EXPECTATION_FAILED = 'The expectation given in an Expect request-header field could not be met by this server, or, if the server is a proxy, the server has unambiguous evidence that the request could not be met by the next-hop server',
I_AM_A_TEAPOT = "This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers",
UNPROCESSABLE_ENTITY = 'The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions',
FAILED_DEPENDENCY = 'The 424 (Failed Dependency) status code means that the method could not be performed on the resource because the requested action depended on another action and that action failed',
TOO_MANY_REQUESTS = 'The 429 status code indicates that the user has sent too many requests in a given amount of time ("rate limiting")',
INTERNAL_SERVER_ERROR = 'The server encountered an unexpected condition which prevented it from fulfilling the request',
NOT_IMPLEMENTED = 'The server does not support the functionality required to fulfill the request',
BAD_GATEWAY = 'The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request',
SERVICE_UNAVAILABLE = 'The server is currently unable to handle the request due to a temporary overloading or maintenance of the server',
GATEWAY_TIMEOUT = 'The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request',
HTTP_VERSION_NOT_SUPPORTED = 'The server does not support, or refuses to support, the HTTP protocol version that was used in the request message',
}

View File

@ -0,0 +1,51 @@
export enum HttpResponseMessages {
CONTINUE = 'Continue',
SWITCHING_PROTOCOLS = 'Switching Protocols',
PROCESSING = 'Processing',
OK = 'OK',
CREATED = 'Created',
ACCEPTED = 'Accepted',
NON_AUTHORITATIVE_INFORMATION = 'Non-Authoritative Information',
NO_CONTENT = 'No Content',
RESET_CONTENT = 'Reset Content',
PARTIAL_CONTENT = 'Partial Content',
AMBIGUOUS = 'Multiple Choices',
MOVED_PERMANENTLY = 'Moved Permanently',
FOUND = 'Found',
SEE_OTHER = 'See Other',
NOT_MODIFIED = 'Not Modified',
TEMPORARY_REDIRECT = 'Temporary Redirect',
PERMANENT_REDIRECT = 'Permanent Redirect',
BAD_REQUEST = 'Bad Request',
UNAUTHORIZED = 'Unauthorized',
PAYMENT_REQUIRED = 'Payment Required',
FORBIDDEN = 'Forbidden',
NOT_FOUND = 'Not Found',
METHOD_NOT_ALLOWED = 'Method Not Allowed',
NOT_ACCEPTABLE = 'Not Acceptable',
PROXY_AUTHENTICATION_REQUIRED = 'Proxy Authentication Required',
REQUEST_TIMEOUT = 'Request Timeout',
CONFLICT = 'Conflict',
GONE = 'Gone',
LENGTH_REQUIRED = 'Length Required',
PRECONDITION_FAILED = 'Precondition Failed',
PAYLOAD_TOO_LARGE = 'Request Entity Too Large',
URI_TOO_LONG = 'Request-URI Too Long',
UNSUPPORTED_MEDIA_TYPE = 'Unsupported Media Type',
REQUESTED_RANGE_NOT_SATISFIABLE = 'Requested Range Not Satisfiable',
EXPECTATION_FAILED = 'Expectation Failed',
I_AM_A_TEAPOT = "I'm a teapot",
UNPROCESSABLE_ENTITY = 'Unprocessable Entity',
FAILED_DEPENDENCY = 'Failed Dependency',
TOO_MANY_REQUESTS = 'Too Many Requests',
INTERNAL_SERVER_ERROR = 'Internal Server Error',
NOT_IMPLEMENTED = 'Not Implemented',
BAD_GATEWAY = 'Bad Gateway',
SERVICE_UNAVAILABLE = 'Service Unavailable',
GATEWAY_TIMEOUT = 'Gateway Timeout',
HTTP_VERSION_NOT_SUPPORTED = 'HTTP Version Not Supported',
}

View File

@ -0,0 +1,7 @@
export enum HttpResponseTypesCodes {
INFORMATIONAL = 1,
SUCCESS = 2,
REDIRECTION = 3,
CLEINT_ERROR = 4,
SERVER_ERROR = 5,
}

View File

@ -0,0 +1,7 @@
export enum HttpResponseTypes {
INFORMATIONAL = 'Informational',
SUCCESS = 'Success',
REDIRECTION = 'Redirection',
CLEINT_ERROR = 'Client Error',
SERVER_ERROR = 'Server Error',
}

View File

@ -0,0 +1,4 @@
export * from './httpResponseDescriptions.enum';
export * from './httpResponseMessages.enum';
export * from './httpResponseTypes.enum';
export * from './httpResponseTypeCodes.enum';

View File

@ -0,0 +1,2 @@
export * from './httpResponse'
export * from './roles.enum'

View File

@ -0,0 +1,21 @@
export enum Roles {
/**
* when the user has a Super admin role that provides the access to all the Superadmin guarded APIs.
*/
Superadmin = 'Superadmin',
/**
* when the user has a Admin role that provides the access to all the Admin guarded APIs.
* It is more restricted than Superadmin role. Superadmin user can provide such a role to the user.
*/
Admin = 'Admin',
/**
* when the user has a User role that provides the access to all the User guarded APIs.
* It is more restricted than Admin role. Admin user can provide such a role to a user.
*/
User = 'User',
/**
* It is a role which is associated to all the users (even non-authorized users). It provides
* some APIs that are going to feed public requirements.
*/
Public = 'Public',
}

1
src/core/domain/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './enums'

View File

@ -0,0 +1,22 @@
export interface HttpResponse {
/**
* Represents the type of the response
*/
type: string;
/**
* Represents the status code of the http response(https://en.wikipedia.org/wiki/List_of_HTTP_status_codes).
*/
status: number;
/**
* Represents a short message about the response status.
*/
message: string;
/**
* Represents a full description about the response (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
*/
description: string;
/**
* Represents the actual data which is returned by the API. In case of empty response we will have it empty also.
*/
data: any;
}

View File

@ -0,0 +1 @@
export * from './http-response.interface';

View File

@ -0,0 +1,18 @@
import { HttpException } from '@nestjs/common';
import { HttpResponse } from '../domain/interfaces';
//==================================================================================================
/**
* implements http exception with http response from the service of common module
*/
export class HttpResponseException extends HttpException {
/**
* Http response exception contructor
* @param data Http response
*/
constructor(data: HttpResponse) {
super(HttpException.createBody(data, data.description, data.status), data.status);
}
}
//==================================================================================================

View File

@ -0,0 +1 @@
export * from './http-response.exception';

1
src/core/guards/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './roles.guard';

View File

@ -0,0 +1,38 @@
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles as Role } from '..//domain/enums';
import { ROLES_KEY } from '../decorators';
/**
* roles guard
*/
@Injectable()
export class RolesGuard implements CanActivate {
//==================================================================================================
/**
* contructs the role guard service
* @param reflector reflector of the guard
*/
constructor(private reflector: Reflector) {}
//==================================================================================================
/**
* checks if the user has allowed permission (role)
* @param context context of the guard (actual information)
* @returns returns true if the user has appropriate role
*/
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) {
return true;
}
const { user } = context.switchToHttp().getRequest();
return user.roles.some((role: Role) => requiredRoles.includes(role));
}
//==================================================================================================
}

View File

@ -0,0 +1,11 @@
import dotenv from 'dotenv';
import { config } from 'dotenv-flow';
import dotenv_expand from 'dotenv-expand';
/**
* Expands the environmanet variables
*/
export function expandEnvVariables(): void {
dotenv.config();
const envConfig = config({ purge_dotenv: true });
dotenv_expand(envConfig);
}

View File

@ -0,0 +1,2 @@
export * from './env.helper';
export * from './util.helper';

View File

@ -0,0 +1,90 @@
import { HttpStatus } from '@nestjs/common';
import { validate } from 'class-validator';
import { HttpResponseException } from '../exceptions';
//==================================================================================================
/**
* processes http error that was throwed by service
* @param error error (exception or string)
* @param logger logger service
*/
export function processMicroserviceHttpError(error: any, logger: any) {
let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
let message = undefined;
let description = undefined;
let data: any = {};
let body: any = {};
if (error instanceof Object && error.response) {
if (error.response._body) body = error.response._body;
if (error.response.data) body = error.response;
if (error.response.statusCode) statusCode = error.response.statusCode;
if (body.data) data = body.data;
if (body.message) message = body.message;
if (body.description) description = body.description;
return { statusCode, message, description, data };
}
if (typeof error == 'string' || error instanceof Object) logger.error(error);
if (error instanceof Error) logger.error(error.message, error);
return { statusCode, message, description, data };
}
//==================================================================================================
/**
* processes http error that was throwed by service
* @param error error (exception or string)
* @param logger logger service
*/
export function processHttpError(error: any, logger: any) {
if (error instanceof HttpResponseException) throw error;
if (typeof error == 'string') logger.error(error);
if (error instanceof Error) logger.error(error.message, error);
}
//==================================================================================================
/**
* validates dto and returns bad request if it is wrong
* @param dto dto
* @param httpResponseGenerator http response service
*/
export async function validateDTO(dto: any, httpResponseGenerator: any): Promise<any> {
const errors = await validate(dto);
if (errors.length) throw new HttpResponseException(httpResponseGenerator.generate(HttpStatus.BAD_REQUEST, errors));
return dto;
}
//==================================================================================================
/**
* validates output dto and throws an error if it is wrong
* @param dto dto
* @param logger logger service
*/
export async function validateOutputDTO(dto: any, logger: any): Promise<any> {
const errors = await validate(dto);
if (errors.length) {
for (const i in errors) {
logger.error(errors[i]);
}
}
return dto;
}
//===================================================================================================
/**
* Takes a number and rounds to a percission number
* @param num number to be rounded
* @param decimalPlaces number of decimal places
* @returns rounded number
*/
export function naiveRound(num:number, decimalPlaces = 2) {
var p = Math.pow(10, decimalPlaces);
return Math.round(num * p) / p;
}

View File

@ -0,0 +1 @@
export * from './logger.interceptor';

View File

@ -0,0 +1,68 @@
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Request, Response } from 'express';
import { LoggerService } from '../services/common'
////////////////////////////////////////////////////////////////////////
/**
* Logs the requests
*/
@Injectable()
export class LoggerInterceptor implements NestInterceptor {
//==================================================================================================
/**
* logs requests for the service
*/
private readonly logger: LoggerService = new LoggerService(LoggerInterceptor.name);
//==================================================================================================
/**
* intercept handler
* @param context context
* @param next next call
* @returns handler
*/
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const startTime = Date.now();
const contextType = context.getType();
return next.handle().pipe(
tap(
() => {
if (contextType === 'http') {
this.logHttpRequest(context, startTime);
}
},
(error: Error) => {
if (contextType === 'http') {
this.logHttpRequest(context, startTime);
} else {
const reqTime = Date.now() - startTime;
this.logger.log(`[${error.name}] ${error.message} ${reqTime}ms`);
}
}
)
);
}
//==================================================================================================
/**
* logs the HTTP requests
* @param context context
* @param startTime start time
* @returns nothing
*/
private logHttpRequest(context: ExecutionContext, startTime: number) {
if (context.getType() !== 'http') return;
const reqTime = Date.now() - startTime;
const controllerName = context.getClass().name;
const handlerName = context.getHandler().name;
const request = context.switchToHttp().getRequest<Request>();
const response = context.switchToHttp().getResponse<Response>();
const { url, method } = request;
const { statusCode } = response;
this.logger.log(
`[HTTP] ${method.toUpperCase()} ${url} ${statusCode} [${controllerName}:${handlerName}] ${reqTime}ms`
);
}
}

View File

@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from '../../application/controller/health.controller'
@Module({
imports: [TerminusModule, HttpModule],
controllers: [HealthController],
})
export class HealthModule {}

View File

@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { HttpResponseService } from '../services/common'
@Module({
providers: [HttpResponseService],
exports: [HttpResponseService],
})
export class HttpResponseModule {}

View File

@ -0,0 +1,3 @@
export * from './http-response.module'
export * from './logger.module'
export * from './health.module'

View File

@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { LoggerService } from '../services/common'
@Module({
providers: [LoggerService, String],
exports: [LoggerService],
})
export class LoggerModule {}

1
src/core/pipes/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './validation.pipe';

View File

@ -0,0 +1,18 @@
import { ValidationError, ValidatorOptions } from 'class-validator';
/**
* env variables validation pipeline
*/
export interface ValidationPipeOptions extends ValidatorOptions {
/**
* If it should be transformed
*/
transform?: boolean;
/**
* If error messages should be disabled
*/
disableErrorMessages?: boolean;
/**
* Exception factory
*/
exceptionFactory?: (errors: ValidationError[]) => any;
}

View File

View File

@ -0,0 +1,73 @@
import { HttpStatus, Injectable } from '@nestjs/common';
import {
HttpResponseDescriptions,
HttpResponseMessages,
HttpResponseTypes,
HttpResponseTypesCodes,
} from '../../domain/enums'
import { HttpResponse } from '../../domain/interfaces';
/**
* HTTP response service
*/
@Injectable()
export class HttpResponseService {
//==================================================================================================
/**
* gets the message
* @param status HTTP status
* @returns message
*/
private getMessage(status: number): string {
return HttpResponseMessages[HttpStatus[status].toString() as keyof typeof HttpResponseMessages];
}
//==================================================================================================
/**
* gets the description
* @param status HTTP status
* @returns description
*/
private getDescription(status: number): string {
return HttpResponseDescriptions[HttpStatus[status].toString() as keyof typeof HttpResponseMessages];
}
//==================================================================================================
/**
* gets the type
* @param status HTTP status
* @returns type
*/
private getType(status: number): string {
return HttpResponseTypes[
HttpResponseTypesCodes[Math.floor(status / 100)].toString() as keyof typeof HttpResponseTypes
];
}
//==================================================================================================
/**
* generates the HTTP response
* @param status HTTP status
* @param data data
* @param message custom message
* @param description custom description
* @returns response
*/
generate(
status: number,
data: unknown = {},
message: string = this.getMessage(status),
description: string = this.getDescription(status)
): HttpResponse {
const response: HttpResponse = {
type: this.getType(status),
status: status,
message: message,
description: description,
data: data,
};
return response;
}
}

View File

@ -0,0 +1,2 @@
export * from './http-response.service';
export * from './logger.service';

View File

@ -0,0 +1,94 @@
import { Injectable, Logger, LoggerService as NestLoggerService } from '@nestjs/common';
import { formatWithOptions } from 'util';
/**
* service for logging
*/
@Injectable()
export class LoggerService implements NestLoggerService {
/**
* logger
*/
private readonly logger: Logger;
/**
* context
*/
private readonly context?: string;
//=============================================================================================================
/**
* constructor for the logger
* @param context
*/
constructor(context: string) {
this.logger = new Logger(context);
this.context = context;
}
//=============================================================================================================
/**
* creates the logger
* @param context context
* @returns logger
*/
static createlogger(context: string): LoggerService {
return new LoggerService(context);
}
//=============================================================================================================
/**
* logs the message
* @param message message
* @param args arguments
*/
public log(message: string, ...args: any[]) {
this.logger.log(this.format(message, args));
}
//=============================================================================================================
/**
* logs the error message
* @param message message
* @param error error
* @param args arguments
*/
public error(message: string, error?: string | Error, ...args: any[]) {
this.logger.error(this.format(message, args), error instanceof Error ? error.stack : error);
}
//=============================================================================================================
/**
* logs the warning message
* @param message message
* @param args arguments
*/
public warn(message: string, ...args: any[]) {
this.logger.warn(this.format(message, args));
}
//=============================================================================================================
/**
* logs the debug message
* @param message message
* @param args arguments
*/
public debug(message: string, ...args: any[]) {
this.logger.debug(this.format(message, args));
}
//=============================================================================================================
/**
* logs the verbose message
* @param message message
* @param args arguments
*/
public verbose(message: string, ...args: any[]) {
this.logger.verbose(this.format(message, args));
}
//=============================================================================================================
/**
* formats the message
* @param message message
* @param args arguments
* @returns formatted message
*/
private format(message: string, args?: string[]) {
if (!args || !args.length) return message;
return formatWithOptions({ colors: true, depth: 5 }, message, ...args);
}
//=============================================================================================================
}

View File

@ -0,0 +1 @@
export * from './common';

View File

@ -0,0 +1,42 @@
import { expandEnvVariables } from '../../core/helpers/env.helper'
expandEnvVariables();
/**
* options enum
*/
export enum EnvObjects {
TRANSACTION_COMMISSION = 'VirtualBankOptions',
WIDRAW_COMMISSION = 'VirtualBankOptions',
DEPOSIT_FEE_PER_MINUTE = 'VirtualBankOptions',
}
//===================================================================================================
/**
* VirtualBank options
*/
export interface VirtualBankOptions {
/**
* Represents the commision amount defined for each money transaction
*/
transaction_commission: number;
/**
* Represents the ammount of commission for each widrawal
*/
widraw_commission: number;
/**
* Represents the fee for each minute more if customer keeps the money in our bank
*/
deposit_fee_per_minute: number;
}
/**
* configuration function
* @returns configuration taken from env
*/
export const configuration = (): any => ({
VirtualBankOptions: {
transaction_commission: process.env.TRANSACTION_COMMISSION,
widraw_commission: process.env.WIDRAW_COMMISSION,
deposit_fee_per_minute: process.env.DEPOSIT_FEE_PER_MINUTE,
},
});

View File

@ -0,0 +1,34 @@
import { plainToClass } from 'class-transformer';
import { validateSync, IsOptional } from 'class-validator';
/**
* env vatiables
*/
class EnvironmentVariables {
/**
* Represents the amount of comission for each transaction
*/
@IsOptional()
TRANSACTION_COMMISSION = 0.001;
@IsOptional()
WIDRAW_COMMISSION = 0.001;
@IsOptional()
DEPOSIT_FEE_PER_MINUTE = 0.0001;
}
/**
* validates the config
* @param config congig
* @returns validated config
*/
export function validate(config: Record<string, unknown>) {
const validatedConfig = plainToClass(EnvironmentVariables, config, { enableImplicitConversion: true });
const errors = validateSync(validatedConfig, { skipMissingProperties: false });
if (errors.length > 0) {
throw new Error(errors.toString());
}
return validatedConfig;
}

View File

@ -0,0 +1,2 @@
export * from './env.objects';
export * from './env.validation';

View File

View File

@ -0,0 +1,45 @@
import { CacheInterceptor, CacheModule, Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { configuration } from '../config/env.objects';
import { validate } from '../config/env.validation';
import { LoggerInterceptor } from '../../core/interceptors'
import * as modules from '../../core/modules'
import { CommonModule } from './common/common.module';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
/**
* application modules list
*/
const modulesList = Object.keys(modules).map(moduleIndex => modules[moduleIndex as keyof typeof modules]);
/**
* application module
*/
@Module({
imports: [
PrometheusModule.register(),
CacheModule.register(),
CommonModule,
ConfigModule.forRoot({
load: [configuration],
validate,
isGlobal: true,
cache: true,
expandVariables: true,
}),
...modulesList,
],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: CacheInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: LoggerInterceptor,
},
],
controllers: [],
})
export class AppModule {}

View File

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { HttpResponseModule } from '../../../core/modules'
import { LoggerModule } from '../../../core/modules'
@Module({
imports: [HttpResponseModule, LoggerModule],
exports: [HttpResponseModule, LoggerModule],
})
export class CommonModule {}

View File

@ -0,0 +1 @@
export * from './common.module';

View File

@ -0,0 +1 @@
export * from './app.module';

48
src/main.ts Normal file
View File

@ -0,0 +1,48 @@
import morgan from 'morgan';
import { Logger, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './infrastructure/modules/app.module';
import { SwaggerModule, DocumentBuilder, SwaggerDocumentOptions } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
/**
* Main entry point of the application
* @returns Nothing
*/
async function bootstrap() {
// Http Server
const app = await NestFactory.create(AppModule);
app.use(morgan('dev'));
app.useGlobalPipes(
new ValidationPipe({
disableErrorMessages: false,
})
);
/**
* Configuration of the Swagger document
*/
const config = new DocumentBuilder()
.setTitle('Nestjs boilerplate')
.setDescription('This is a nest clean architecture boilerplate')
.setVersion('0.0.1')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
try {
const configService = app.get(ConfigService);
const NODE_PORT = configService.get('NODE_PORT');
if (!NODE_PORT) {
throw new Error('Please define the node port as an environmental variable');
}
await app.listen(NODE_PORT, () => Logger.log('HTTP Service is listening on port ' + String(NODE_PORT), 'App'));
} catch (error) {
console.log(error);
return;
}
}
//==================================================================================================================================
bootstrap();

0
test/.gitkeep Normal file
View File

15
tsconfig.build.json Normal file
View File

@ -0,0 +1,15 @@
{
"extends": "./tsconfig.json",
"exclude": [
"node_modules",
"dist",
"test",
"e2e",
"prod",
"integration"
],
"include": [
"src"
],
}

33
tsconfig.json Normal file
View File

@ -0,0 +1,33 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"useDefineForClassFields": false,
"target": "ESNext",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"allowJs": true,
"incremental": true,
"skipLibCheck": true,
"esModuleInterop": true,
"moduleResolution": "Node",
"resolveJsonModule": true
},
"include": [
"src",
"./src/**/*.ts",
"test",
"e2e",
"integration"
],
"exclude": [
"node_modules",
"dist",
"prod"
]
}