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.
Files changed (94) hide show
  1. package/README.kr.md +5 -6
  2. package/README.md +5 -4
  3. package/lib/default/package.json +7 -10
  4. package/lib/default/src/http/auth.http +0 -5
  5. package/lib/default/swagger.yaml +0 -3
  6. package/lib/graphql/.env.development.local +1 -1
  7. package/lib/graphql/.env.production.local +1 -1
  8. package/lib/graphql/package.json +6 -9
  9. package/lib/knex/.env.development.local +1 -1
  10. package/lib/knex/.env.production.local +1 -1
  11. package/lib/knex/package.json +21 -24
  12. package/lib/knex/src/http/auth.http +0 -5
  13. package/lib/knex/swagger.yaml +0 -3
  14. package/lib/mikro-orm/.dockerignore +18 -0
  15. package/lib/mikro-orm/.editorconfig +9 -0
  16. package/lib/mikro-orm/.env.development.local +18 -0
  17. package/lib/mikro-orm/.env.production.local +18 -0
  18. package/lib/mikro-orm/.env.test.local +18 -0
  19. package/lib/mikro-orm/.eslintignore +1 -0
  20. package/lib/mikro-orm/.eslintrc +18 -0
  21. package/lib/mikro-orm/.huskyrc +5 -0
  22. package/lib/mikro-orm/.lintstagedrc.json +5 -0
  23. package/lib/mikro-orm/.prettierrc +8 -0
  24. package/lib/mikro-orm/.swcrc +41 -0
  25. package/lib/mikro-orm/.vscode/launch.json +35 -0
  26. package/lib/mikro-orm/.vscode/settings.json +6 -0
  27. package/lib/mikro-orm/Dockerfile +24 -0
  28. package/lib/mikro-orm/Makefile +29 -0
  29. package/lib/mikro-orm/docker-compose.yml +46 -0
  30. package/lib/mikro-orm/ecosystem.config.js +57 -0
  31. package/lib/mikro-orm/jest.config.js +12 -0
  32. package/lib/mikro-orm/nginx.conf +40 -0
  33. package/lib/mikro-orm/nodemon.json +12 -0
  34. package/lib/mikro-orm/package.json +77 -0
  35. package/lib/mikro-orm/src/app.ts +98 -0
  36. package/lib/mikro-orm/src/config/index.ts +5 -0
  37. package/lib/mikro-orm/src/controllers/auth.controller.ts +46 -0
  38. package/lib/mikro-orm/src/controllers/index.controller.ts +13 -0
  39. package/lib/mikro-orm/src/controllers/users.controller.ts +65 -0
  40. package/lib/mikro-orm/src/databases/index.ts +19 -0
  41. package/lib/mikro-orm/src/dtos/users.dto.ts +9 -0
  42. package/lib/mikro-orm/src/entities/base.entity.ts +16 -0
  43. package/lib/mikro-orm/src/entities/users.entity.ts +17 -0
  44. package/lib/mikro-orm/src/exceptions/HttpException.ts +10 -0
  45. package/lib/mikro-orm/src/http/auth.http +32 -0
  46. package/lib/mikro-orm/src/http/users.http +34 -0
  47. package/lib/mikro-orm/src/interfaces/auth.interface.ts +15 -0
  48. package/lib/mikro-orm/src/interfaces/routes.interface.ts +6 -0
  49. package/lib/mikro-orm/src/interfaces/users.interface.ts +5 -0
  50. package/lib/mikro-orm/src/middlewares/auth.middleware.ts +32 -0
  51. package/lib/mikro-orm/src/middlewares/error.middleware.ts +17 -0
  52. package/lib/mikro-orm/src/middlewares/validation.middleware.ts +25 -0
  53. package/lib/mikro-orm/src/routes/auth.route.ts +24 -0
  54. package/lib/mikro-orm/src/routes/index.route.ts +19 -0
  55. package/lib/mikro-orm/src/routes/users.route.ts +25 -0
  56. package/lib/mikro-orm/src/server.ts +11 -0
  57. package/lib/mikro-orm/src/services/auth.service.ts +63 -0
  58. package/lib/mikro-orm/src/services/users.service.ts +68 -0
  59. package/lib/mikro-orm/src/tests/auth.test.ts +66 -0
  60. package/lib/mikro-orm/src/tests/index.test.ts +18 -0
  61. package/lib/mikro-orm/src/tests/users.test.ts +70 -0
  62. package/lib/mikro-orm/src/utils/logger.ts +65 -0
  63. package/lib/mikro-orm/src/utils/util.ts +19 -0
  64. package/lib/mikro-orm/src/utils/validateEnv.ts +10 -0
  65. package/lib/mikro-orm/swagger.yaml +122 -0
  66. package/lib/mikro-orm/tsconfig.json +41 -0
  67. package/lib/mongoose/.env.development.local +1 -1
  68. package/lib/mongoose/.env.production.local +1 -1
  69. package/lib/mongoose/package.json +5 -8
  70. package/lib/mongoose/src/http/auth.http +0 -5
  71. package/lib/mongoose/swagger.yaml +0 -2
  72. package/lib/prisma/.env.development.local +1 -1
  73. package/lib/prisma/.env.production.local +1 -1
  74. package/lib/prisma/package.json +5 -8
  75. package/lib/prisma/src/http/auth.http +0 -5
  76. package/lib/prisma/swagger.yaml +0 -3
  77. package/lib/routing-controllers/package.json +6 -8
  78. package/lib/routing-controllers/src/http/auth.http +0 -5
  79. package/lib/sequelize/.env.development.local +1 -1
  80. package/lib/sequelize/.env.production.local +1 -1
  81. package/lib/sequelize/package.json +5 -8
  82. package/lib/sequelize/src/http/auth.http +0 -5
  83. package/lib/sequelize/swagger.yaml +0 -3
  84. package/lib/typegoose/.env.development.local +1 -1
  85. package/lib/typegoose/.env.production.local +1 -1
  86. package/lib/typegoose/package.json +4 -7
  87. package/lib/typegoose/src/http/auth.http +0 -5
  88. package/lib/typegoose/swagger.yaml +0 -2
  89. package/lib/typeorm/.env.development.local +1 -1
  90. package/lib/typeorm/.env.production.local +1 -1
  91. package/lib/typeorm/package.json +4 -7
  92. package/lib/typeorm/src/http/auth.http +0 -5
  93. package/lib/typeorm/swagger.yaml +0 -3
  94. package/package.json +6 -15
@@ -0,0 +1,25 @@
1
+ import { plainToClass } from 'class-transformer';
2
+ import { validate, ValidationError } from 'class-validator';
3
+ import { RequestHandler } from 'express';
4
+ import { HttpException } from '@exceptions/HttpException';
5
+
6
+ const validationMiddleware = (
7
+ type: any,
8
+ value: string | 'body' | 'query' | 'params' = 'body',
9
+ skipMissingProperties = false,
10
+ whitelist = true,
11
+ forbidNonWhitelisted = true,
12
+ ): RequestHandler => {
13
+ return (req, res, next) => {
14
+ validate(plainToClass(type, req[value]), { skipMissingProperties, whitelist, forbidNonWhitelisted }).then((errors: ValidationError[]) => {
15
+ if (errors.length > 0) {
16
+ const message = errors.map((error: ValidationError) => Object.values(error.constraints)).join(', ');
17
+ next(new HttpException(400, message));
18
+ } else {
19
+ next();
20
+ }
21
+ });
22
+ };
23
+ };
24
+
25
+ export default validationMiddleware;
@@ -0,0 +1,24 @@
1
+ import { Router } from 'express';
2
+ import AuthController from '@controllers/auth.controller';
3
+ import { CreateUserDto } from '@dtos/users.dto';
4
+ import { Routes } from '@interfaces/routes.interface';
5
+ import authMiddleware from '@middlewares/auth.middleware';
6
+ import validationMiddleware from '@middlewares/validation.middleware';
7
+
8
+ class AuthRoute implements Routes {
9
+ public path = '/';
10
+ public router = Router();
11
+ public authController = new AuthController();
12
+
13
+ constructor() {
14
+ this.initializeRoutes();
15
+ }
16
+
17
+ private initializeRoutes() {
18
+ this.router.post(`${this.path}signup`, validationMiddleware(CreateUserDto, 'body'), this.authController.signUp);
19
+ this.router.post(`${this.path}login`, validationMiddleware(CreateUserDto, 'body'), this.authController.logIn);
20
+ this.router.post(`${this.path}logout`, authMiddleware, this.authController.logOut);
21
+ }
22
+ }
23
+
24
+ export default AuthRoute;
@@ -0,0 +1,19 @@
1
+ import { Router } from 'express';
2
+ import IndexController from '@controllers/index.controller';
3
+ import { Routes } from '@interfaces/routes.interface';
4
+
5
+ class IndexRoute implements Routes {
6
+ public path = '/';
7
+ public router = Router();
8
+ public indexController = new IndexController();
9
+
10
+ constructor() {
11
+ this.initializeRoutes();
12
+ }
13
+
14
+ private initializeRoutes() {
15
+ this.router.get(`${this.path}`, this.indexController.index);
16
+ }
17
+ }
18
+
19
+ export default IndexRoute;
@@ -0,0 +1,25 @@
1
+ import { Router } from 'express';
2
+ import UsersController from '@controllers/users.controller';
3
+ import { CreateUserDto } from '@dtos/users.dto';
4
+ import { Routes } from '@interfaces/routes.interface';
5
+ import validationMiddleware from '@middlewares/validation.middleware';
6
+
7
+ class UsersRoute implements Routes {
8
+ public path = '/users';
9
+ public router = Router();
10
+ public usersController = new UsersController();
11
+
12
+ constructor() {
13
+ this.initializeRoutes();
14
+ }
15
+
16
+ private initializeRoutes() {
17
+ this.router.get(`${this.path}`, this.usersController.getUsers);
18
+ this.router.get(`${this.path}/:id`, this.usersController.getUserById);
19
+ this.router.post(`${this.path}`, validationMiddleware(CreateUserDto, 'body'), this.usersController.createUser);
20
+ this.router.put(`${this.path}/:id`, validationMiddleware(CreateUserDto, 'body', true), this.usersController.updateUser);
21
+ this.router.delete(`${this.path}/:id`, this.usersController.deleteUser);
22
+ }
23
+ }
24
+
25
+ export default UsersRoute;
@@ -0,0 +1,11 @@
1
+ import App from '@/app';
2
+ import AuthRoute from '@routes/auth.route';
3
+ import IndexRoute from '@routes/index.route';
4
+ import UsersRoute from '@routes/users.route';
5
+ import validateEnv from '@utils/validateEnv';
6
+
7
+ validateEnv();
8
+
9
+ const app = new App([new IndexRoute(), new UsersRoute(), new AuthRoute()]);
10
+
11
+ app.listen();
@@ -0,0 +1,63 @@
1
+ import { hash, compare } from 'bcrypt';
2
+ import { sign } from 'jsonwebtoken';
3
+ import { SECRET_KEY } from '@config';
4
+ import { DI } from '@databases';
5
+ import { CreateUserDto } from '@dtos/users.dto';
6
+ import { HttpException } from '@exceptions/HttpException';
7
+ import { DataStoredInToken, TokenData } from '@interfaces/auth.interface';
8
+ import { User } from '@interfaces/users.interface';
9
+ import { isEmpty } from '@utils/util';
10
+
11
+ class AuthService {
12
+ public async signup(userData: CreateUserDto): Promise<User> {
13
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
14
+
15
+ const findUser: User = await DI.userRepository.findOne({ email: userData.email });
16
+ if (findUser) throw new HttpException(409, `You're email ${userData.email} already exists`);
17
+
18
+ const hashedPassword = await hash(userData.password, 10);
19
+ const createUserData: User = DI.userRepository.create({ ...userData, password: hashedPassword });
20
+
21
+ await DI.em.persistAndFlush(createUserData);
22
+
23
+ return createUserData;
24
+ }
25
+
26
+ public async login(userData: CreateUserDto): Promise<{ cookie: string; findUser: User }> {
27
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
28
+
29
+ const findUser: User = await DI.userRepository.findOne({ email: userData.email });
30
+ if (!findUser) throw new HttpException(409, `You're email ${userData.email} not found`);
31
+
32
+ const isPasswordMatching: boolean = await compare(userData.password, findUser.password);
33
+ if (!isPasswordMatching) throw new HttpException(409, "You're password not matching");
34
+
35
+ const tokenData = this.createToken(findUser);
36
+ const cookie = this.createCookie(tokenData);
37
+
38
+ return { cookie, findUser };
39
+ }
40
+
41
+ public async logout(userData: User): Promise<User> {
42
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
43
+
44
+ const findUser: User = await DI.userRepository.findOne({ email: userData.email, password: userData.password });
45
+ if (!findUser) throw new HttpException(409, `You're email ${userData.email} not found`);
46
+
47
+ return findUser;
48
+ }
49
+
50
+ public createToken(user: User): TokenData {
51
+ const dataStoredInToken: DataStoredInToken = { _id: user.id };
52
+ const secretKey: string = SECRET_KEY;
53
+ const expiresIn: number = 60 * 60;
54
+
55
+ return { expiresIn, token: sign(dataStoredInToken, secretKey, { expiresIn }) };
56
+ }
57
+
58
+ public createCookie(tokenData: TokenData): string {
59
+ return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn};`;
60
+ }
61
+ }
62
+
63
+ export default AuthService;
@@ -0,0 +1,68 @@
1
+ import { hash } from 'bcrypt';
2
+ import { wrap } from '@mikro-orm/core';
3
+ import { DI } from '@databases';
4
+ import { CreateUserDto } from '@dtos/users.dto';
5
+ import { HttpException } from '@exceptions/HttpException';
6
+ import { User } from '@interfaces/users.interface';
7
+ import { isEmpty } from '@utils/util';
8
+
9
+ class UserService {
10
+ public async findAllUser(): Promise<User[]> {
11
+ const users: User[] = await DI.userRepository.findAll();
12
+ return users;
13
+ }
14
+
15
+ public async findUserById(userId: string): Promise<User> {
16
+ if (isEmpty(userId)) throw new HttpException(400, "You're not userId");
17
+
18
+ const findUser: User = await DI.userRepository.findOne(userId);
19
+ if (!findUser) throw new HttpException(409, "You're not user");
20
+
21
+ return findUser;
22
+ }
23
+
24
+ public async createUser(userData: CreateUserDto): Promise<User> {
25
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
26
+
27
+ const findUser: User = await DI.userRepository.findOne({ email: userData.email });
28
+ if (findUser) throw new HttpException(409, `You're email ${userData.email} already exists`);
29
+
30
+ const hashedPassword = await hash(userData.password, 10);
31
+ const createUserData: User = DI.userRepository.create({ ...userData, password: hashedPassword });
32
+
33
+ await DI.em.persistAndFlush(createUserData);
34
+
35
+ return createUserData;
36
+ }
37
+
38
+ public async updateUser(userId: string, userData: CreateUserDto): Promise<User> {
39
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
40
+
41
+ if (userData.email) {
42
+ const findUser: User = await DI.userRepository.findOne({ email: userData.email });
43
+ if (findUser && findUser.id !== userId) throw new HttpException(409, `You're email ${userData.email} already exists`);
44
+ }
45
+
46
+ if (userData.password) {
47
+ const hashedPassword = await hash(userData.password, 10);
48
+ userData = { ...userData, password: hashedPassword };
49
+ }
50
+
51
+ const updateUserById: User = await DI.userRepository.findOne(userId);
52
+ wrap(updateUserById).assign(userData);
53
+ if (!updateUserById) throw new HttpException(409, "You're not user");
54
+
55
+ return updateUserById;
56
+ }
57
+
58
+ public async deleteUser(userId: string): Promise<User> {
59
+ const findUser = await DI.userRepository.findOne(userId);
60
+
61
+ if (!findUser) throw new HttpException(409, "You're not user");
62
+ await DI.userRepository.removeAndFlush(findUser);
63
+
64
+ return findUser;
65
+ }
66
+ }
67
+
68
+ export default UserService;
@@ -0,0 +1,66 @@
1
+ import request from 'supertest';
2
+ import App from '../app';
3
+ import { DI } from '../databases';
4
+ import { CreateUserDto } from '../dtos/users.dto';
5
+ import AuthRoute from '../routes/auth.route';
6
+
7
+ const authRoute = new AuthRoute();
8
+
9
+ const app = new App([authRoute]);
10
+
11
+ let cookies: string;
12
+
13
+ /**
14
+ ** MikroORM Seeding
15
+ ** https://mikro-orm.io/docs/seeding#use-in-tests
16
+ */
17
+
18
+ beforeAll(async () => {
19
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
20
+
21
+ await DI.orm.getSchemaGenerator().refreshDatabase();
22
+ });
23
+
24
+ afterAll(async () => {
25
+ await DI.orm.close();
26
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
27
+ });
28
+
29
+ describe('Testing Auth', () => {
30
+ describe('[POST] /signup', () => {
31
+ it('response should have the Create userData', async () => {
32
+ const userData: CreateUserDto = {
33
+ email: 'test@email.com',
34
+ password: 'q1w2e3r4!',
35
+ };
36
+ return request(app.getServer()).post(`${authRoute.path}signup`).send(userData);
37
+ });
38
+ });
39
+ describe('[POST] /login', () => {
40
+ it('response should have the Set-Cookie header with the Authorization token', async () => {
41
+ const userData: CreateUserDto = {
42
+ email: 'test@email.com',
43
+ password: 'q1w2e3r4!',
44
+ };
45
+ const res = await request(app.getServer())
46
+ .post(`${authRoute.path}login`)
47
+ .send(userData)
48
+ .expect('Set-Cookie', /^Authorization=.+/);
49
+
50
+ cookies = res.headers['set-cookie'];
51
+ });
52
+ });
53
+ describe('[POST] /logout', () => {
54
+ it('logout Set-Cookie Authorization=; Max-age=0', async () => {
55
+ const userData: CreateUserDto = {
56
+ email: 'test@email.com',
57
+ password: 'q1w2e3r4!',
58
+ };
59
+ return request(app.getServer())
60
+ .post(`${authRoute.path}logout`)
61
+ .send(userData)
62
+ .set('Cookie', cookies)
63
+ .expect('Set-Cookie', /^Authorization=\; Max-age=0/);
64
+ });
65
+ });
66
+ });
@@ -0,0 +1,18 @@
1
+ import request from 'supertest';
2
+ import App from '../app';
3
+ import IndexRoute from '../routes/index.route';
4
+
5
+ afterAll(async () => {
6
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
7
+ });
8
+
9
+ describe('Testing Index', () => {
10
+ describe('[GET] /', () => {
11
+ it('response statusCode 200', () => {
12
+ const indexRoute = new IndexRoute();
13
+ const app = new App([indexRoute]);
14
+
15
+ return request(app.getServer()).get(`${indexRoute.path}`).expect(200);
16
+ });
17
+ });
18
+ });
@@ -0,0 +1,70 @@
1
+ import request from 'supertest';
2
+ import App from '../app';
3
+ import { DI } from '../databases';
4
+ import { CreateUserDto } from '../dtos/users.dto';
5
+ import UsersRoute from '../routes/users.route';
6
+
7
+ const usersRoute = new UsersRoute();
8
+
9
+ const app = new App([usersRoute]);
10
+
11
+ let userId: string;
12
+
13
+ /**
14
+ ** MikroORM Seeding
15
+ ** https://mikro-orm.io/docs/seeding#use-in-tests
16
+ */
17
+
18
+ beforeAll(async () => {
19
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
20
+
21
+ await DI.orm.getSchemaGenerator().refreshDatabase();
22
+ });
23
+
24
+ afterAll(async () => {
25
+ await DI.orm.close();
26
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
27
+ });
28
+
29
+ describe('Testing Users', () => {
30
+ describe('[GET] /users', () => {
31
+ it('response fineAll Users', async () => {
32
+ return request(app.getServer()).get(`${usersRoute.path}`).expect(200);
33
+ });
34
+ });
35
+
36
+ describe('[POST] /users', () => {
37
+ it('response Create User', async () => {
38
+ const userData: CreateUserDto = {
39
+ email: 'test@email.com',
40
+ password: 'q1w2e3r4',
41
+ };
42
+
43
+ const { body } = await request(app.getServer()).post(`${usersRoute.path}`).send(userData).expect(201);
44
+ userId = body.data.id;
45
+ });
46
+ });
47
+
48
+ describe('[GET] /users/:id', () => {
49
+ it('response findOne User', async () => {
50
+ return await request(app.getServer()).get(`${usersRoute.path}/${userId}`).expect(200);
51
+ });
52
+ });
53
+
54
+ describe('[PUT] /users/:id', () => {
55
+ it('response Update User', async () => {
56
+ const userData: CreateUserDto = {
57
+ email: 'test1@email.com',
58
+ password: 'q1w2e3r4',
59
+ };
60
+
61
+ return await request(app.getServer()).put(`${usersRoute.path}/${userId}`).send(userData).expect(200);
62
+ });
63
+ });
64
+
65
+ describe('[DELETE] /users/:id', () => {
66
+ it('response Delete User', async () => {
67
+ return request(app.getServer()).delete(`${usersRoute.path}/${userId}`).expect(200);
68
+ });
69
+ });
70
+ });
@@ -0,0 +1,65 @@
1
+ import { existsSync, mkdirSync } from 'fs';
2
+ import { join } from 'path';
3
+ import winston from 'winston';
4
+ import winstonDaily from 'winston-daily-rotate-file';
5
+ import { LOG_DIR } from '@config';
6
+
7
+ // logs dir
8
+ const logDir: string = join(__dirname, LOG_DIR);
9
+
10
+ if (!existsSync(logDir)) {
11
+ mkdirSync(logDir);
12
+ }
13
+
14
+ // Define log format
15
+ const logFormat = winston.format.printf(({ timestamp, level, message }) => `${timestamp} ${level}: ${message}`);
16
+
17
+ /*
18
+ * Log Level
19
+ * error: 0, warn: 1, info: 2, http: 3, verbose: 4, debug: 5, silly: 6
20
+ */
21
+ const logger = winston.createLogger({
22
+ format: winston.format.combine(
23
+ winston.format.timestamp({
24
+ format: 'YYYY-MM-DD HH:mm:ss',
25
+ }),
26
+ logFormat,
27
+ ),
28
+ transports: [
29
+ // debug log setting
30
+ new winstonDaily({
31
+ level: 'debug',
32
+ datePattern: 'YYYY-MM-DD',
33
+ dirname: logDir + '/debug', // log file /logs/debug/*.log in save
34
+ filename: `%DATE%.log`,
35
+ maxFiles: 30, // 30 Days saved
36
+ json: false,
37
+ zippedArchive: true,
38
+ }),
39
+ // error log setting
40
+ new winstonDaily({
41
+ level: 'error',
42
+ datePattern: 'YYYY-MM-DD',
43
+ dirname: logDir + '/error', // log file /logs/error/*.log in save
44
+ filename: `%DATE%.log`,
45
+ maxFiles: 30, // 30 Days saved
46
+ handleExceptions: true,
47
+ json: false,
48
+ zippedArchive: true,
49
+ }),
50
+ ],
51
+ });
52
+
53
+ logger.add(
54
+ new winston.transports.Console({
55
+ format: winston.format.combine(winston.format.splat(), winston.format.colorize()),
56
+ }),
57
+ );
58
+
59
+ const stream = {
60
+ write: (message: string) => {
61
+ logger.info(message.substring(0, message.lastIndexOf('\n')));
62
+ },
63
+ };
64
+
65
+ export { logger, stream };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @method isEmpty
3
+ * @param {String | Number | Object} value
4
+ * @returns {Boolean} true & false
5
+ * @description this value is Empty Check
6
+ */
7
+ export const isEmpty = (value: string | number | object): boolean => {
8
+ if (value === null) {
9
+ return true;
10
+ } else if (typeof value !== 'number' && value === '') {
11
+ return true;
12
+ } else if (typeof value === 'undefined' || value === undefined) {
13
+ return true;
14
+ } else if (value !== null && typeof value === 'object' && !Object.keys(value).length) {
15
+ return true;
16
+ } else {
17
+ return false;
18
+ }
19
+ };
@@ -0,0 +1,10 @@
1
+ import { cleanEnv, port, str } from 'envalid';
2
+
3
+ const validateEnv = () => {
4
+ cleanEnv(process.env, {
5
+ NODE_ENV: str(),
6
+ PORT: port(),
7
+ });
8
+ };
9
+
10
+ export default validateEnv;
@@ -0,0 +1,122 @@
1
+ tags:
2
+ - name: users
3
+ description: users API
4
+
5
+ paths:
6
+ # [GET] users
7
+ /users:
8
+ get:
9
+ tags:
10
+ - users
11
+ summary: Find All Users
12
+ responses:
13
+ 200:
14
+ description: 'OK'
15
+ 500:
16
+ description: 'Server Error'
17
+
18
+ # [POST] users
19
+ post:
20
+ tags:
21
+ - users
22
+ summary: Add User
23
+ parameters:
24
+ - name: body
25
+ in: body
26
+ description: user Data
27
+ required: true
28
+ schema:
29
+ $ref: '#/definitions/users'
30
+ responses:
31
+ 201:
32
+ description: 'Created'
33
+ 400:
34
+ description: 'Bad Request'
35
+ 409:
36
+ description: 'Conflict'
37
+ 500:
38
+ description: 'Server Error'
39
+
40
+ # [GET] users/id
41
+ /users/{id}:
42
+ get:
43
+ tags:
44
+ - users
45
+ summary: Find User By Id
46
+ parameters:
47
+ - name: id
48
+ in: path
49
+ description: User Id
50
+ required: true
51
+ responses:
52
+ 200:
53
+ description: 'OK'
54
+ 409:
55
+ description: 'Conflict'
56
+ 500:
57
+ description: 'Server Error'
58
+
59
+ # [PUT] users/id
60
+ put:
61
+ tags:
62
+ - users
63
+ summary: Update User By Id
64
+ parameters:
65
+ - name: id
66
+ in: path
67
+ description: user Id
68
+ required: true
69
+ - name: body
70
+ in: body
71
+ description: user Data
72
+ required: true
73
+ schema:
74
+ $ref: '#/definitions/users'
75
+ responses:
76
+ 200:
77
+ description: 'OK'
78
+ 400:
79
+ description: 'Bad Request'
80
+ 409:
81
+ description: 'Conflict'
82
+ 500:
83
+ description: 'Server Error'
84
+
85
+ # [DELETE] users/id
86
+ delete:
87
+ tags:
88
+ - users
89
+ summary: Delete User By Id
90
+ parameters:
91
+ - name: id
92
+ in: path
93
+ description: user Id
94
+ required: true
95
+ responses:
96
+ 200:
97
+ description: 'OK'
98
+ 409:
99
+ description: 'Conflict'
100
+ 500:
101
+ description: 'Server Error'
102
+
103
+ # definitions
104
+ definitions:
105
+ users:
106
+ type: object
107
+ required:
108
+ - email
109
+ - password
110
+ properties:
111
+ id:
112
+ description: user Id
113
+ email:
114
+ type: string
115
+ description: user Email
116
+ password:
117
+ type: string
118
+ description: user Password
119
+
120
+ schemes:
121
+ - https
122
+ - http
@@ -0,0 +1,41 @@
1
+ {
2
+ "compileOnSave": false,
3
+ "compilerOptions": {
4
+ "target": "es2017",
5
+ "lib": ["es2017", "esnext.asynciterable"],
6
+ "typeRoots": ["node_modules/@types"],
7
+ "allowSyntheticDefaultImports": true,
8
+ "experimentalDecorators": true,
9
+ "emitDecoratorMetadata": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "moduleResolution": "node",
12
+ "module": "commonjs",
13
+ "pretty": true,
14
+ "sourceMap": true,
15
+ "declaration": true,
16
+ "outDir": "dist",
17
+ "allowJs": true,
18
+ "noEmit": false,
19
+ "esModuleInterop": true,
20
+ "resolveJsonModule": true,
21
+ "importHelpers": true,
22
+ "baseUrl": "src",
23
+ "paths": {
24
+ "@/*": ["*"],
25
+ "@config": ["config"],
26
+ "@controllers/*": ["controllers/*"],
27
+ "@databases": ["databases"],
28
+ "@dtos/*": ["dtos/*"],
29
+ "@entities/*": ["entities/*"],
30
+ "@exceptions/*": ["exceptions/*"],
31
+ "@interfaces/*": ["interfaces/*"],
32
+ "@middlewares/*": ["middlewares/*"],
33
+ "@models/*": ["models/*"],
34
+ "@routes/*": ["routes/*"],
35
+ "@services/*": ["services/*"],
36
+ "@utils/*": ["utils/*"]
37
+ }
38
+ },
39
+ "include": ["src/**/*.ts", "src/**/*.json", ".env"],
40
+ "exclude": ["node_modules", "src/http", "src/logs", "src/tests"]
41
+ }
@@ -4,7 +4,7 @@ PORT = 3000
4
4
  # DATABASE
5
5
  DB_HOST = localhost
6
6
  DB_PORT = 27017
7
- DB_DATABASE = test
7
+ DB_DATABASE = dev
8
8
 
9
9
  # TOKEN
10
10
  SECRET_KEY = secretKey
@@ -4,7 +4,7 @@ PORT = 3000
4
4
  # DATABASE
5
5
  DB_HOST = localhost
6
6
  DB_PORT = 27017
7
- DB_DATABASE = test
7
+ DB_DATABASE = prod
8
8
 
9
9
  # TOKEN
10
10
  SECRET_KEY = secretKey