typescript-express-starter 8.1.7 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.kr.md +5 -6
- package/README.md +5 -4
- package/lib/default/package.json +7 -10
- package/lib/default/src/http/auth.http +0 -5
- package/lib/default/swagger.yaml +0 -3
- package/lib/graphql/.env.development.local +1 -1
- package/lib/graphql/.env.production.local +1 -1
- package/lib/graphql/package.json +6 -9
- package/lib/knex/.env.development.local +1 -1
- package/lib/knex/.env.production.local +1 -1
- package/lib/knex/package.json +21 -24
- package/lib/knex/src/http/auth.http +0 -5
- package/lib/knex/swagger.yaml +0 -3
- package/lib/mikro-orm/.dockerignore +18 -0
- package/lib/mikro-orm/.editorconfig +9 -0
- package/lib/mikro-orm/.env.development.local +18 -0
- package/lib/mikro-orm/.env.production.local +18 -0
- package/lib/mikro-orm/.env.test.local +18 -0
- package/lib/mikro-orm/.eslintignore +1 -0
- package/lib/mikro-orm/.eslintrc +18 -0
- package/lib/mikro-orm/.huskyrc +5 -0
- package/lib/mikro-orm/.lintstagedrc.json +5 -0
- package/lib/mikro-orm/.prettierrc +8 -0
- package/lib/mikro-orm/.swcrc +41 -0
- package/lib/mikro-orm/.vscode/launch.json +35 -0
- package/lib/mikro-orm/.vscode/settings.json +6 -0
- package/lib/mikro-orm/Dockerfile +24 -0
- package/lib/mikro-orm/Makefile +29 -0
- package/lib/mikro-orm/docker-compose.yml +46 -0
- package/lib/mikro-orm/ecosystem.config.js +57 -0
- package/lib/mikro-orm/jest.config.js +12 -0
- package/lib/mikro-orm/nginx.conf +40 -0
- package/lib/mikro-orm/nodemon.json +12 -0
- package/lib/mikro-orm/package.json +77 -0
- package/lib/mikro-orm/src/app.ts +98 -0
- package/lib/mikro-orm/src/config/index.ts +5 -0
- package/lib/mikro-orm/src/controllers/auth.controller.ts +46 -0
- package/lib/mikro-orm/src/controllers/index.controller.ts +13 -0
- package/lib/mikro-orm/src/controllers/users.controller.ts +65 -0
- package/lib/mikro-orm/src/databases/index.ts +19 -0
- package/lib/mikro-orm/src/dtos/users.dto.ts +9 -0
- package/lib/mikro-orm/src/entities/base.entity.ts +16 -0
- package/lib/mikro-orm/src/entities/users.entity.ts +17 -0
- package/lib/mikro-orm/src/exceptions/HttpException.ts +10 -0
- package/lib/mikro-orm/src/http/auth.http +32 -0
- package/lib/mikro-orm/src/http/users.http +34 -0
- package/lib/mikro-orm/src/interfaces/auth.interface.ts +15 -0
- package/lib/mikro-orm/src/interfaces/routes.interface.ts +6 -0
- package/lib/mikro-orm/src/interfaces/users.interface.ts +5 -0
- package/lib/mikro-orm/src/middlewares/auth.middleware.ts +32 -0
- package/lib/mikro-orm/src/middlewares/error.middleware.ts +17 -0
- package/lib/mikro-orm/src/middlewares/validation.middleware.ts +25 -0
- package/lib/mikro-orm/src/routes/auth.route.ts +24 -0
- package/lib/mikro-orm/src/routes/index.route.ts +19 -0
- package/lib/mikro-orm/src/routes/users.route.ts +25 -0
- package/lib/mikro-orm/src/server.ts +11 -0
- package/lib/mikro-orm/src/services/auth.service.ts +63 -0
- package/lib/mikro-orm/src/services/users.service.ts +68 -0
- package/lib/mikro-orm/src/tests/auth.test.ts +66 -0
- package/lib/mikro-orm/src/tests/index.test.ts +18 -0
- package/lib/mikro-orm/src/tests/users.test.ts +70 -0
- package/lib/mikro-orm/src/utils/logger.ts +65 -0
- package/lib/mikro-orm/src/utils/util.ts +19 -0
- package/lib/mikro-orm/src/utils/validateEnv.ts +10 -0
- package/lib/mikro-orm/swagger.yaml +122 -0
- package/lib/mikro-orm/tsconfig.json +41 -0
- package/lib/mongoose/.env.development.local +1 -1
- package/lib/mongoose/.env.production.local +1 -1
- package/lib/mongoose/package.json +5 -8
- package/lib/mongoose/src/http/auth.http +0 -5
- package/lib/mongoose/swagger.yaml +0 -2
- package/lib/prisma/.env.development.local +1 -1
- package/lib/prisma/.env.production.local +1 -1
- package/lib/prisma/package.json +5 -8
- package/lib/prisma/src/http/auth.http +0 -5
- package/lib/prisma/swagger.yaml +0 -3
- package/lib/routing-controllers/package.json +6 -8
- package/lib/routing-controllers/src/http/auth.http +0 -5
- package/lib/sequelize/.env.development.local +1 -1
- package/lib/sequelize/.env.production.local +1 -1
- package/lib/sequelize/package.json +5 -8
- package/lib/sequelize/src/http/auth.http +0 -5
- package/lib/sequelize/swagger.yaml +0 -3
- package/lib/typegoose/.env.development.local +1 -1
- package/lib/typegoose/.env.production.local +1 -1
- package/lib/typegoose/package.json +4 -7
- package/lib/typegoose/src/http/auth.http +0 -5
- package/lib/typegoose/swagger.yaml +0 -2
- package/lib/typeorm/.env.development.local +1 -1
- package/lib/typeorm/.env.production.local +1 -1
- package/lib/typeorm/package.json +4 -7
- package/lib/typeorm/src/http/auth.http +0 -5
- package/lib/typeorm/swagger.yaml +0 -3
- package/package.json +6 -15
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @description pm2 configuration file.
|
|
3
|
+
* @example
|
|
4
|
+
* production mode :: pm2 start ecosystem.config.js --only prod
|
|
5
|
+
* development mode :: pm2 start ecosystem.config.js --only dev
|
|
6
|
+
*/
|
|
7
|
+
module.exports = {
|
|
8
|
+
apps: [
|
|
9
|
+
{
|
|
10
|
+
name: 'prod', // pm2 start App name
|
|
11
|
+
script: 'dist/server.js',
|
|
12
|
+
exec_mode: 'cluster', // 'cluster' or 'fork'
|
|
13
|
+
instance_var: 'INSTANCE_ID', // instance variable
|
|
14
|
+
instances: 2, // pm2 instance count
|
|
15
|
+
autorestart: true, // auto restart if process crash
|
|
16
|
+
watch: false, // files change automatic restart
|
|
17
|
+
ignore_watch: ['node_modules', 'logs'], // ignore files change
|
|
18
|
+
max_memory_restart: '1G', // restart if process use more than 1G memory
|
|
19
|
+
merge_logs: true, // if true, stdout and stderr will be merged and sent to pm2 log
|
|
20
|
+
output: './logs/access.log', // pm2 log file
|
|
21
|
+
error: './logs/error.log', // pm2 error log file
|
|
22
|
+
env: { // environment variable
|
|
23
|
+
PORT: 3000,
|
|
24
|
+
NODE_ENV: 'production',
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
name: 'dev', // pm2 start App name
|
|
29
|
+
script: 'ts-node', // ts-node
|
|
30
|
+
args: '-r tsconfig-paths/register --transpile-only src/server.ts', // ts-node args
|
|
31
|
+
exec_mode: 'cluster', // 'cluster' or 'fork'
|
|
32
|
+
instance_var: 'INSTANCE_ID', // instance variable
|
|
33
|
+
instances: 2, // pm2 instance count
|
|
34
|
+
autorestart: true, // auto restart if process crash
|
|
35
|
+
watch: false, // files change automatic restart
|
|
36
|
+
ignore_watch: ['node_modules', 'logs'], // ignore files change
|
|
37
|
+
max_memory_restart: '1G', // restart if process use more than 1G memory
|
|
38
|
+
merge_logs: true, // if true, stdout and stderr will be merged and sent to pm2 log
|
|
39
|
+
output: './logs/access.log', // pm2 log file
|
|
40
|
+
error: './logs/error.log', // pm2 error log file
|
|
41
|
+
env: { // environment variable
|
|
42
|
+
PORT: 3000,
|
|
43
|
+
NODE_ENV: 'development',
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
],
|
|
47
|
+
deploy: {
|
|
48
|
+
production: {
|
|
49
|
+
user: 'user',
|
|
50
|
+
host: '0.0.0.0',
|
|
51
|
+
ref: 'origin/master',
|
|
52
|
+
repo: 'git@github.com:repo.git',
|
|
53
|
+
path: 'dist/server.js',
|
|
54
|
+
'post-deploy': 'npm install && npm run build && pm2 reload ecosystem.config.js --only prod',
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const { pathsToModuleNameMapper } = require('ts-jest');
|
|
2
|
+
const { compilerOptions } = require('./tsconfig.json');
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
preset: 'ts-jest',
|
|
6
|
+
testEnvironment: 'node',
|
|
7
|
+
roots: ['<rootDir>/src'],
|
|
8
|
+
transform: {
|
|
9
|
+
'^.+\\.tsx?$': 'ts-jest',
|
|
10
|
+
},
|
|
11
|
+
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/src' }),
|
|
12
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
user nginx;
|
|
2
|
+
worker_processes 1;
|
|
3
|
+
|
|
4
|
+
error_log /var/log/nginx/error.log warn;
|
|
5
|
+
pid /var/run/nginx.pid;
|
|
6
|
+
|
|
7
|
+
events {
|
|
8
|
+
worker_connections 1024;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
http {
|
|
12
|
+
include /etc/nginx/mime.types;
|
|
13
|
+
default_type application/octet-stream;
|
|
14
|
+
|
|
15
|
+
upstream api-server {
|
|
16
|
+
server server:3000;
|
|
17
|
+
keepalive 100;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
server {
|
|
21
|
+
listen 80;
|
|
22
|
+
server_name localhost;
|
|
23
|
+
|
|
24
|
+
location / {
|
|
25
|
+
proxy_http_version 1.1;
|
|
26
|
+
proxy_pass http://api-server;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
|
32
|
+
'$status $body_bytes_sent "$http_referer" '
|
|
33
|
+
'"$http_user_agent" "$http_x_forwarded_for"';
|
|
34
|
+
|
|
35
|
+
access_log /var/log/nginx/access.log main;
|
|
36
|
+
|
|
37
|
+
sendfile on;
|
|
38
|
+
keepalive_timeout 65;
|
|
39
|
+
include /etc/nginx/conf.d/*.conf;
|
|
40
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "typescript-express-starter",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "TypeScript + MikroORM + MongoDB + Express API Server",
|
|
5
|
+
"author": "",
|
|
6
|
+
"license": "ISC",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"start": "npm run build && cross-env NODE_ENV=production node dist/server.js",
|
|
9
|
+
"dev": "cross-env NODE_ENV=development nodemon",
|
|
10
|
+
"build": "swc src -d dist --source-maps --copy-files",
|
|
11
|
+
"build:tsc": "tsc && tsc-alias",
|
|
12
|
+
"test": "jest --forceExit --detectOpenHandles",
|
|
13
|
+
"lint": "eslint --ext .ts src/",
|
|
14
|
+
"lint:fix": "npm run lint -- --fix",
|
|
15
|
+
"deploy:prod": "npm run build && pm2 start ecosystem.config.js --only prod",
|
|
16
|
+
"deploy:dev": "pm2 start ecosystem.config.js --only dev"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@mikro-orm/core": "^5.1.2",
|
|
20
|
+
"@mikro-orm/mongodb": "^5.1.2",
|
|
21
|
+
"bcrypt": "^5.0.1",
|
|
22
|
+
"class-transformer": "^0.5.1",
|
|
23
|
+
"class-validator": "^0.13.1",
|
|
24
|
+
"compression": "^1.7.4",
|
|
25
|
+
"cookie-parser": "^1.4.5",
|
|
26
|
+
"cors": "^2.8.5",
|
|
27
|
+
"dotenv": "^10.0.0",
|
|
28
|
+
"envalid": "^7.1.0",
|
|
29
|
+
"express": "^4.17.1",
|
|
30
|
+
"helmet": "^4.6.0",
|
|
31
|
+
"hpp": "^0.2.3",
|
|
32
|
+
"jsonwebtoken": "^8.5.1",
|
|
33
|
+
"morgan": "^1.10.0",
|
|
34
|
+
"swagger-jsdoc": "^6.0.0",
|
|
35
|
+
"swagger-ui-express": "^4.1.6",
|
|
36
|
+
"winston": "^3.3.3",
|
|
37
|
+
"winston-daily-rotate-file": "^4.5.5"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@mikro-orm/mongo-highlighter": "^1.0.0",
|
|
41
|
+
"@swc/cli": "^0.1.51",
|
|
42
|
+
"@swc/core": "^1.2.108",
|
|
43
|
+
"@types/bcrypt": "^5.0.0",
|
|
44
|
+
"@types/compression": "^1.7.1",
|
|
45
|
+
"@types/cookie-parser": "^1.4.2",
|
|
46
|
+
"@types/cors": "^2.8.11",
|
|
47
|
+
"@types/express": "^4.17.13",
|
|
48
|
+
"@types/hpp": "^0.2.1",
|
|
49
|
+
"@types/jest": "27.4.x",
|
|
50
|
+
"@types/jsonwebtoken": "^8.5.4",
|
|
51
|
+
"@types/morgan": "^1.9.3",
|
|
52
|
+
"@types/node": "^16.0.1",
|
|
53
|
+
"@types/supertest": "^2.0.11",
|
|
54
|
+
"@types/swagger-jsdoc": "^6.0.1",
|
|
55
|
+
"@types/swagger-ui-express": "^4.1.3",
|
|
56
|
+
"@typescript-eslint/eslint-plugin": "^4.28.2",
|
|
57
|
+
"@typescript-eslint/parser": "^4.28.2",
|
|
58
|
+
"cross-env": "^7.0.3",
|
|
59
|
+
"eslint": "^7.30.0",
|
|
60
|
+
"eslint-config-prettier": "^8.3.0",
|
|
61
|
+
"eslint-plugin-prettier": "^3.4.0",
|
|
62
|
+
"husky": "^7.0.1",
|
|
63
|
+
"jest": "27.4.x",
|
|
64
|
+
"lint-staged": "^11.0.0",
|
|
65
|
+
"node-config": "^0.0.2",
|
|
66
|
+
"node-gyp": "^8.1.0",
|
|
67
|
+
"nodemon": "^2.0.9",
|
|
68
|
+
"pm2": "^5.1.0",
|
|
69
|
+
"prettier": "^2.3.2",
|
|
70
|
+
"supertest": "^6.2.2",
|
|
71
|
+
"ts-jest": "^27.1.4",
|
|
72
|
+
"ts-node": "^10.4.0",
|
|
73
|
+
"tsc-alias": "^1.4.1",
|
|
74
|
+
"tsconfig-paths": "^3.10.1",
|
|
75
|
+
"typescript": "^4.5.2"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import cookieParser from 'cookie-parser';
|
|
3
|
+
import compression from 'compression';
|
|
4
|
+
import cors from 'cors';
|
|
5
|
+
import helmet from 'helmet';
|
|
6
|
+
import hpp from 'hpp';
|
|
7
|
+
import morgan from 'morgan';
|
|
8
|
+
import swaggerJSDoc from 'swagger-jsdoc';
|
|
9
|
+
import swaggerUi from 'swagger-ui-express';
|
|
10
|
+
import { logger, stream } from '@utils/logger';
|
|
11
|
+
import { MikroORM, RequestContext } from '@mikro-orm/core';
|
|
12
|
+
import { NODE_ENV, PORT, LOG_FORMAT, ORIGIN, CREDENTIALS } from '@config';
|
|
13
|
+
import { DI, dbOptions } from '@databases';
|
|
14
|
+
import { UserEntity } from '@entities/users.entity';
|
|
15
|
+
import { Routes } from '@interfaces/routes.interface';
|
|
16
|
+
import errorMiddleware from '@middlewares/error.middleware';
|
|
17
|
+
|
|
18
|
+
class App {
|
|
19
|
+
public app: express.Application;
|
|
20
|
+
public env: string;
|
|
21
|
+
public port: string | number;
|
|
22
|
+
public host: string;
|
|
23
|
+
|
|
24
|
+
constructor(routes: Routes[]) {
|
|
25
|
+
this.app = express();
|
|
26
|
+
this.env = NODE_ENV || 'development';
|
|
27
|
+
this.port = PORT || 3000;
|
|
28
|
+
|
|
29
|
+
this.initializeMiddlewares();
|
|
30
|
+
this.connectToDatabase();
|
|
31
|
+
this.initializeRoutes(routes);
|
|
32
|
+
this.initializeSwagger();
|
|
33
|
+
this.initializeErrorHandling();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
public listen() {
|
|
37
|
+
this.app.listen(this.port, () => {
|
|
38
|
+
logger.info(`=================================`);
|
|
39
|
+
logger.info(`======= ENV: ${this.env} =======`);
|
|
40
|
+
logger.info(`🚀 App listening on the port ${this.port}`);
|
|
41
|
+
logger.info(`=================================`);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public getServer() {
|
|
46
|
+
return this.app;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private async connectToDatabase() {
|
|
50
|
+
try {
|
|
51
|
+
DI.orm = await MikroORM.init(dbOptions);
|
|
52
|
+
DI.em = DI.orm.em.fork();
|
|
53
|
+
DI.userRepository = DI.orm.em.fork().getRepository(UserEntity);
|
|
54
|
+
} catch (error) {
|
|
55
|
+
logger.error(error);
|
|
56
|
+
}
|
|
57
|
+
this.app.use((_1, _2, next) => RequestContext.create(DI.orm.em, next));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
private initializeMiddlewares() {
|
|
61
|
+
this.app.use(morgan(LOG_FORMAT, { stream }));
|
|
62
|
+
this.app.use(cors({ origin: ORIGIN, credentials: CREDENTIALS }));
|
|
63
|
+
this.app.use(hpp());
|
|
64
|
+
this.app.use(helmet());
|
|
65
|
+
this.app.use(compression());
|
|
66
|
+
this.app.use(express.json());
|
|
67
|
+
this.app.use(express.urlencoded({ extended: true }));
|
|
68
|
+
this.app.use(cookieParser());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private initializeRoutes(routes: Routes[]) {
|
|
72
|
+
routes.forEach(route => {
|
|
73
|
+
this.app.use('/', route.router);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private initializeSwagger() {
|
|
78
|
+
const options = {
|
|
79
|
+
swaggerDefinition: {
|
|
80
|
+
info: {
|
|
81
|
+
title: 'REST API',
|
|
82
|
+
version: '1.0.0',
|
|
83
|
+
description: 'Example docs',
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
apis: ['swagger.yaml'],
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const specs = swaggerJSDoc(options);
|
|
90
|
+
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private initializeErrorHandling() {
|
|
94
|
+
this.app.use(errorMiddleware);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export default App;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { config } from 'dotenv';
|
|
2
|
+
config({ path: `.env.${process.env.NODE_ENV || 'development'}.local` });
|
|
3
|
+
|
|
4
|
+
export const CREDENTIALS = process.env.CREDENTIALS === 'true';
|
|
5
|
+
export const { NODE_ENV, PORT, DB_HOST, DB_PORT, DB_DATABASE, SECRET_KEY, LOG_FORMAT, LOG_DIR, ORIGIN } = process.env;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { NextFunction, Request, Response } from 'express';
|
|
2
|
+
import { CreateUserDto } from '@dtos/users.dto';
|
|
3
|
+
import { RequestWithUser } from '@interfaces/auth.interface';
|
|
4
|
+
import { User } from '@interfaces/users.interface';
|
|
5
|
+
import AuthService from '@services/auth.service';
|
|
6
|
+
|
|
7
|
+
class AuthController {
|
|
8
|
+
public authService = new AuthService();
|
|
9
|
+
|
|
10
|
+
public signUp = async (req: Request, res: Response, next: NextFunction) => {
|
|
11
|
+
try {
|
|
12
|
+
const userData: CreateUserDto = req.body;
|
|
13
|
+
const signUpUserData: User = await this.authService.signup(userData);
|
|
14
|
+
|
|
15
|
+
res.status(201).json({ data: signUpUserData, message: 'signup' });
|
|
16
|
+
} catch (error) {
|
|
17
|
+
next(error);
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
public logIn = async (req: Request, res: Response, next: NextFunction) => {
|
|
22
|
+
try {
|
|
23
|
+
const userData: CreateUserDto = req.body;
|
|
24
|
+
const { cookie, findUser } = await this.authService.login(userData);
|
|
25
|
+
|
|
26
|
+
res.setHeader('Set-Cookie', [cookie]);
|
|
27
|
+
res.status(200).json({ data: findUser, message: 'login' });
|
|
28
|
+
} catch (error) {
|
|
29
|
+
next(error);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
public logOut = async (req: RequestWithUser, res: Response, next: NextFunction) => {
|
|
34
|
+
try {
|
|
35
|
+
const userData: User = req.user;
|
|
36
|
+
const logOutUserData: User = await this.authService.logout(userData);
|
|
37
|
+
|
|
38
|
+
res.setHeader('Set-Cookie', ['Authorization=; Max-age=0']);
|
|
39
|
+
res.status(200).json({ data: logOutUserData, message: 'logout' });
|
|
40
|
+
} catch (error) {
|
|
41
|
+
next(error);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export default AuthController;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { NextFunction, Request, Response } from 'express';
|
|
2
|
+
|
|
3
|
+
class IndexController {
|
|
4
|
+
public index = (req: Request, res: Response, next: NextFunction) => {
|
|
5
|
+
try {
|
|
6
|
+
res.sendStatus(200);
|
|
7
|
+
} catch (error) {
|
|
8
|
+
next(error);
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default IndexController;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { NextFunction, Request, Response } from 'express';
|
|
2
|
+
import { CreateUserDto } from '@dtos/users.dto';
|
|
3
|
+
import { User } from '@interfaces/users.interface';
|
|
4
|
+
import userService from '@services/users.service';
|
|
5
|
+
|
|
6
|
+
class UsersController {
|
|
7
|
+
public userService = new userService();
|
|
8
|
+
|
|
9
|
+
public getUsers = async (req: Request, res: Response, next: NextFunction) => {
|
|
10
|
+
try {
|
|
11
|
+
const findAllUsersData: User[] = await this.userService.findAllUser();
|
|
12
|
+
|
|
13
|
+
res.status(200).json({ data: findAllUsersData, message: 'findAll' });
|
|
14
|
+
} catch (error) {
|
|
15
|
+
next(error);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
public getUserById = async (req: Request, res: Response, next: NextFunction) => {
|
|
20
|
+
try {
|
|
21
|
+
const userId: string = req.params.id;
|
|
22
|
+
const findOneUserData: User = await this.userService.findUserById(userId);
|
|
23
|
+
|
|
24
|
+
res.status(200).json({ data: findOneUserData, message: 'findOne' });
|
|
25
|
+
} catch (error) {
|
|
26
|
+
next(error);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
public createUser = async (req: Request, res: Response, next: NextFunction) => {
|
|
31
|
+
try {
|
|
32
|
+
const userData: CreateUserDto = req.body;
|
|
33
|
+
const createUserData: User = await this.userService.createUser(userData);
|
|
34
|
+
|
|
35
|
+
res.status(201).json({ data: createUserData, message: 'created' });
|
|
36
|
+
} catch (error) {
|
|
37
|
+
next(error);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
public updateUser = async (req: Request, res: Response, next: NextFunction) => {
|
|
42
|
+
try {
|
|
43
|
+
const userId: string = req.params.id;
|
|
44
|
+
const userData: CreateUserDto = req.body;
|
|
45
|
+
const updateUserData: User = await this.userService.updateUser(userId, userData);
|
|
46
|
+
|
|
47
|
+
res.status(200).json({ data: updateUserData, message: 'updated' });
|
|
48
|
+
} catch (error) {
|
|
49
|
+
next(error);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
public deleteUser = async (req: Request, res: Response, next: NextFunction) => {
|
|
54
|
+
try {
|
|
55
|
+
const userId: string = req.params.id;
|
|
56
|
+
const deleteUserData = await this.userService.deleteUser(userId);
|
|
57
|
+
|
|
58
|
+
res.status(200).json({ data: deleteUserData, message: 'deleted' });
|
|
59
|
+
} catch (error) {
|
|
60
|
+
next(error);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export default UsersController;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { EntityManager, EntityRepository, MikroORM, Options } from '@mikro-orm/core';
|
|
2
|
+
import { MongoHighlighter } from '@mikro-orm/mongo-highlighter';
|
|
3
|
+
import { NODE_ENV, DB_HOST, DB_PORT, DB_DATABASE } from '@config';
|
|
4
|
+
import { BaseEntity } from '@entities/base.entity';
|
|
5
|
+
import { UserEntity } from '@entities/users.entity';
|
|
6
|
+
|
|
7
|
+
export const dbOptions: Options = {
|
|
8
|
+
type: 'mongo',
|
|
9
|
+
clientUrl: `mongodb://${DB_HOST}:${DB_PORT}/${DB_DATABASE}`,
|
|
10
|
+
entities: [BaseEntity, UserEntity],
|
|
11
|
+
highlighter: new MongoHighlighter(),
|
|
12
|
+
debug: NODE_ENV === 'development' ? true : false,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const DI = {} as {
|
|
16
|
+
orm: MikroORM;
|
|
17
|
+
em: EntityManager;
|
|
18
|
+
userRepository: EntityRepository<UserEntity>;
|
|
19
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { PrimaryKey, Property, SerializedPrimaryKey } from '@mikro-orm/core';
|
|
2
|
+
import { ObjectId } from '@mikro-orm/mongodb';
|
|
3
|
+
|
|
4
|
+
export abstract class BaseEntity {
|
|
5
|
+
@PrimaryKey()
|
|
6
|
+
_id!: ObjectId;
|
|
7
|
+
|
|
8
|
+
@SerializedPrimaryKey({ type: 'text' })
|
|
9
|
+
id!: string;
|
|
10
|
+
|
|
11
|
+
@Property({ type: 'date' })
|
|
12
|
+
createdAt = new Date();
|
|
13
|
+
|
|
14
|
+
@Property({ type: 'date', onUpdate: () => new Date() })
|
|
15
|
+
updatedAt = new Date();
|
|
16
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Entity, Property } from '@mikro-orm/core';
|
|
2
|
+
import { BaseEntity } from '@entities/base.entity';
|
|
3
|
+
|
|
4
|
+
@Entity()
|
|
5
|
+
export class UserEntity extends BaseEntity {
|
|
6
|
+
constructor(email: string, password: string) {
|
|
7
|
+
super();
|
|
8
|
+
this.email = email;
|
|
9
|
+
this.password = password;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
@Property({ type: 'text' })
|
|
13
|
+
email!: string;
|
|
14
|
+
|
|
15
|
+
@Property({ type: 'text' })
|
|
16
|
+
password!: string;
|
|
17
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# baseURL
|
|
2
|
+
@baseURL = http://localhost:3000
|
|
3
|
+
|
|
4
|
+
###
|
|
5
|
+
# User Signup
|
|
6
|
+
POST {{ baseURL }}/signup
|
|
7
|
+
Content-Type: application/json
|
|
8
|
+
|
|
9
|
+
{
|
|
10
|
+
"email": "example@email.com",
|
|
11
|
+
"password": "password"
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
###
|
|
15
|
+
# User Login
|
|
16
|
+
POST {{ baseURL }}/login
|
|
17
|
+
Content-Type: application/json
|
|
18
|
+
|
|
19
|
+
{
|
|
20
|
+
"email": "example@email.com",
|
|
21
|
+
"password": "password"
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
###
|
|
25
|
+
# User Logout
|
|
26
|
+
POST {{ baseURL }}/logout
|
|
27
|
+
Content-Type: application/json
|
|
28
|
+
|
|
29
|
+
{
|
|
30
|
+
"email": "example@email.com",
|
|
31
|
+
"password": "password"
|
|
32
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# baseURL
|
|
2
|
+
@baseURL = http://localhost:3000
|
|
3
|
+
|
|
4
|
+
###
|
|
5
|
+
# Find All Users
|
|
6
|
+
GET {{ baseURL }}/users
|
|
7
|
+
|
|
8
|
+
###
|
|
9
|
+
# Find User By Id
|
|
10
|
+
GET {{ baseURL }}/users/6257233cbfa5c2b8e249dbe7
|
|
11
|
+
|
|
12
|
+
###
|
|
13
|
+
# Create User
|
|
14
|
+
POST {{ baseURL }}/users
|
|
15
|
+
Content-Type: application/json
|
|
16
|
+
|
|
17
|
+
{
|
|
18
|
+
"email": "example@email.com",
|
|
19
|
+
"password": "password"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
###
|
|
23
|
+
# Modify User By Id
|
|
24
|
+
PUT {{ baseURL }}/users/6257233cbfa5c2b8e249dbe7
|
|
25
|
+
Content-Type: application/json
|
|
26
|
+
|
|
27
|
+
{
|
|
28
|
+
"email": "example@email.com",
|
|
29
|
+
"password": "password"
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
###
|
|
33
|
+
# Delete User By Id
|
|
34
|
+
DELETE {{ baseURL }}/users/6257233cbfa5c2b8e249dbe7
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Request } from 'express';
|
|
2
|
+
import { User } from '@interfaces/users.interface';
|
|
3
|
+
|
|
4
|
+
export interface DataStoredInToken {
|
|
5
|
+
_id: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface TokenData {
|
|
9
|
+
token: string;
|
|
10
|
+
expiresIn: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface RequestWithUser extends Request {
|
|
14
|
+
user: User;
|
|
15
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { NextFunction, Response } from 'express';
|
|
2
|
+
import { verify } from 'jsonwebtoken';
|
|
3
|
+
import { SECRET_KEY } from '@config';
|
|
4
|
+
import { DI } from '@databases';
|
|
5
|
+
import { HttpException } from '@exceptions/HttpException';
|
|
6
|
+
import { DataStoredInToken, RequestWithUser } from '@interfaces/auth.interface';
|
|
7
|
+
|
|
8
|
+
const authMiddleware = async (req: RequestWithUser, res: Response, next: NextFunction) => {
|
|
9
|
+
try {
|
|
10
|
+
const Authorization = req.cookies['Authorization'] || (req.header('Authorization') ? req.header('Authorization').split('Bearer ')[1] : null);
|
|
11
|
+
|
|
12
|
+
if (Authorization) {
|
|
13
|
+
const secretKey: string = SECRET_KEY;
|
|
14
|
+
const verificationResponse = verify(Authorization, secretKey) as DataStoredInToken;
|
|
15
|
+
const userId = verificationResponse._id;
|
|
16
|
+
const findUser = await DI.userRepository.findOne(userId);
|
|
17
|
+
|
|
18
|
+
if (findUser) {
|
|
19
|
+
req.user = findUser;
|
|
20
|
+
next();
|
|
21
|
+
} else {
|
|
22
|
+
next(new HttpException(401, 'Wrong authentication token'));
|
|
23
|
+
}
|
|
24
|
+
} else {
|
|
25
|
+
next(new HttpException(404, 'Authentication token missing'));
|
|
26
|
+
}
|
|
27
|
+
} catch (error) {
|
|
28
|
+
next(new HttpException(401, 'Wrong authentication token'));
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export default authMiddleware;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { NextFunction, Request, Response } from 'express';
|
|
2
|
+
import { HttpException } from '@exceptions/HttpException';
|
|
3
|
+
import { logger } from '@utils/logger';
|
|
4
|
+
|
|
5
|
+
const errorMiddleware = (error: HttpException, req: Request, res: Response, next: NextFunction) => {
|
|
6
|
+
try {
|
|
7
|
+
const status: number = error.status || 500;
|
|
8
|
+
const message: string = error.message || 'Something went wrong';
|
|
9
|
+
|
|
10
|
+
logger.error(`[${req.method}] ${req.path} >> StatusCode:: ${status}, Message:: ${message}`);
|
|
11
|
+
res.status(status).json({ message });
|
|
12
|
+
} catch (error) {
|
|
13
|
+
next(error);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export default errorMiddleware;
|