typescript-express-starter 6.1.0 → 7.0.0

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 (184) hide show
  1. package/README.kr.md +122 -53
  2. package/README.md +127 -59
  3. package/bin/cli.js +4 -3
  4. package/lib/default/.swcrc +41 -0
  5. package/lib/default/Dockerfile +1 -1
  6. package/lib/default/ecosystem.config.js +40 -24
  7. package/lib/default/nodemon.json +2 -2
  8. package/lib/default/package.json +15 -8
  9. package/lib/default/src/app.ts +1 -2
  10. package/lib/default/src/http/auth.http +12 -15
  11. package/lib/default/src/http/users.http +12 -16
  12. package/lib/default/src/index.ts +1 -0
  13. package/lib/default/src/middlewares/auth.middleware.ts +3 -3
  14. package/lib/default/src/models/users.model.ts +5 -5
  15. package/lib/default/src/server.ts +1 -2
  16. package/lib/default/src/services/auth.service.ts +5 -5
  17. package/lib/default/src/services/users.service.ts +3 -3
  18. package/lib/default/src/tests/auth.test.ts +4 -4
  19. package/lib/default/src/tests/users.test.ts +4 -4
  20. package/lib/default/src/utils/logger.ts +5 -5
  21. package/lib/default/tsconfig.json +2 -2
  22. package/lib/graphql/.dockerignore +18 -0
  23. package/lib/graphql/.editorconfig +9 -0
  24. package/lib/graphql/.env +1 -0
  25. package/lib/graphql/.eslintignore +1 -0
  26. package/lib/graphql/.eslintrc +18 -0
  27. package/lib/graphql/.huskyrc +5 -0
  28. package/lib/graphql/.lintstagedrc.json +5 -0
  29. package/lib/graphql/.prettierrc +8 -0
  30. package/lib/graphql/.swcrc +39 -0
  31. package/lib/graphql/.vscode/launch.json +35 -0
  32. package/lib/graphql/.vscode/settings.json +6 -0
  33. package/lib/graphql/Dockerfile +24 -0
  34. package/lib/graphql/Makefile +6 -0
  35. package/lib/graphql/docker-compose.yml +50 -0
  36. package/lib/graphql/ecosystem.config.js +59 -0
  37. package/lib/graphql/jest.config.js +12 -0
  38. package/lib/graphql/nginx.conf +40 -0
  39. package/lib/graphql/nodemon.json +12 -0
  40. package/lib/graphql/package.json +79 -0
  41. package/lib/graphql/src/app.ts +105 -0
  42. package/lib/graphql/src/configs/development.json +19 -0
  43. package/lib/graphql/src/configs/production.json +19 -0
  44. package/lib/graphql/src/configs/test.json +19 -0
  45. package/lib/graphql/src/databases/index.ts +24 -0
  46. package/lib/graphql/src/dtos/users.dto.ts +14 -0
  47. package/lib/{typeorm/src/entity → graphql/src/entities}/users.entity.ts +3 -3
  48. package/lib/graphql/src/exceptions/HttpException.ts +10 -0
  49. package/lib/graphql/src/http/auth.http +49 -0
  50. package/lib/graphql/src/http/users.http +78 -0
  51. package/lib/graphql/src/index.ts +1 -0
  52. package/lib/graphql/src/interfaces/auth.interface.ts +14 -0
  53. package/lib/graphql/src/interfaces/db.interface.ts +7 -0
  54. package/lib/graphql/src/interfaces/users.interface.ts +5 -0
  55. package/lib/graphql/src/middlewares/auth.middleware.ts +32 -0
  56. package/lib/graphql/src/middlewares/error.middleware.ts +17 -0
  57. package/lib/graphql/src/repositories/auth.repository.ts +61 -0
  58. package/lib/graphql/src/repositories/users.repository.ts +60 -0
  59. package/lib/graphql/src/resolvers/auth.resolver.ts +32 -0
  60. package/lib/graphql/src/resolvers/users.resolver.ts +47 -0
  61. package/lib/graphql/src/server.ts +14 -0
  62. package/lib/graphql/src/tests/auth.test.ts +52 -0
  63. package/lib/graphql/src/tests/index.test.ts +18 -0
  64. package/lib/graphql/src/tests/users.test.ts +71 -0
  65. package/lib/graphql/src/typedefs/users.type.ts +13 -0
  66. package/lib/graphql/src/utils/logger.ts +75 -0
  67. package/lib/graphql/src/utils/util.ts +19 -0
  68. package/lib/graphql/src/utils/validateEnv.ts +10 -0
  69. package/lib/graphql/tsconfig.json +39 -0
  70. package/lib/knex/.swcrc +39 -0
  71. package/lib/knex/Dockerfile +1 -1
  72. package/lib/knex/ecosystem.config.js +57 -43
  73. package/lib/knex/knexfile.ts +6 -6
  74. package/lib/knex/nodemon.json +2 -2
  75. package/lib/knex/package.json +14 -8
  76. package/lib/knex/src/app.ts +2 -3
  77. package/lib/knex/src/databases/index.ts +6 -6
  78. package/lib/knex/src/http/auth.http +12 -15
  79. package/lib/knex/src/http/users.http +12 -16
  80. package/lib/knex/src/index.ts +1 -0
  81. package/lib/knex/src/middlewares/auth.middleware.ts +4 -4
  82. package/lib/knex/src/server.ts +1 -2
  83. package/lib/knex/src/services/auth.service.ts +5 -5
  84. package/lib/knex/src/services/users.service.ts +3 -3
  85. package/lib/knex/src/tests/auth.test.ts +2 -2
  86. package/lib/knex/src/tests/index.test.ts +1 -1
  87. package/lib/knex/src/tests/users.test.ts +2 -2
  88. package/lib/knex/src/utils/logger.ts +5 -5
  89. package/lib/knex/tsconfig.json +2 -2
  90. package/lib/mongoose/.swcrc +39 -0
  91. package/lib/mongoose/Dockerfile +1 -1
  92. package/lib/mongoose/docker-compose.yml +0 -4
  93. package/lib/mongoose/ecosystem.config.js +42 -27
  94. package/lib/mongoose/nodemon.json +2 -2
  95. package/lib/mongoose/package.json +15 -8
  96. package/lib/mongoose/src/app.ts +2 -3
  97. package/lib/mongoose/src/configs/development.json +1 -1
  98. package/lib/mongoose/src/configs/production.json +1 -1
  99. package/lib/mongoose/src/configs/test.json +1 -1
  100. package/lib/mongoose/src/http/auth.http +32 -0
  101. package/lib/mongoose/src/http/users.http +34 -0
  102. package/lib/mongoose/src/index.ts +1 -0
  103. package/lib/mongoose/src/middlewares/auth.middleware.ts +3 -3
  104. package/lib/mongoose/src/server.ts +1 -2
  105. package/lib/mongoose/src/services/auth.service.ts +5 -5
  106. package/lib/mongoose/src/services/users.service.ts +3 -3
  107. package/lib/mongoose/src/utils/logger.ts +5 -5
  108. package/lib/mongoose/tsconfig.json +2 -2
  109. package/lib/prisma/.env +1 -1
  110. package/lib/prisma/.swcrc +37 -0
  111. package/lib/prisma/Dockerfile +1 -1
  112. package/lib/prisma/docker-compose.yml +1 -6
  113. package/lib/prisma/ecosystem.config.js +40 -24
  114. package/lib/prisma/nodemon.json +2 -2
  115. package/lib/prisma/package.json +17 -10
  116. package/lib/prisma/src/app.ts +2 -3
  117. package/lib/prisma/src/http/auth.http +12 -15
  118. package/lib/prisma/src/http/users.http +12 -16
  119. package/lib/prisma/src/index.ts +1 -0
  120. package/lib/prisma/src/middlewares/auth.middleware.ts +4 -4
  121. package/lib/prisma/src/server.ts +1 -2
  122. package/lib/prisma/src/services/auth.service.ts +5 -5
  123. package/lib/prisma/src/services/users.service.ts +3 -3
  124. package/lib/prisma/src/utils/logger.ts +5 -5
  125. package/lib/prisma/tsconfig.json +2 -2
  126. package/lib/routing-controllers/.swcrc +37 -0
  127. package/lib/routing-controllers/Dockerfile +1 -1
  128. package/lib/routing-controllers/ecosystem.config.js +40 -24
  129. package/lib/routing-controllers/nodemon.json +2 -2
  130. package/lib/routing-controllers/package.json +15 -9
  131. package/lib/routing-controllers/src/app.ts +3 -4
  132. package/lib/routing-controllers/src/http/auth.http +12 -15
  133. package/lib/routing-controllers/src/http/users.http +12 -16
  134. package/lib/routing-controllers/src/index.ts +1 -0
  135. package/lib/routing-controllers/src/middlewares/auth.middleware.ts +3 -3
  136. package/lib/routing-controllers/src/middlewares/validation.middleware.ts +10 -2
  137. package/lib/routing-controllers/src/models/users.model.ts +5 -5
  138. package/lib/routing-controllers/src/server.ts +1 -3
  139. package/lib/routing-controllers/src/services/auth.service.ts +5 -5
  140. package/lib/routing-controllers/src/services/users.service.ts +3 -3
  141. package/lib/routing-controllers/src/utils/logger.ts +5 -5
  142. package/lib/routing-controllers/tsconfig.json +2 -2
  143. package/lib/sequelize/.swcrc +39 -0
  144. package/lib/sequelize/Dockerfile +1 -1
  145. package/lib/sequelize/docker-compose.yml +1 -6
  146. package/lib/sequelize/ecosystem.config.js +42 -27
  147. package/lib/sequelize/nodemon.json +2 -2
  148. package/lib/sequelize/package.json +15 -8
  149. package/lib/sequelize/src/app.ts +1 -2
  150. package/lib/sequelize/src/configs/development.json +2 -2
  151. package/lib/sequelize/src/configs/production.json +1 -1
  152. package/lib/sequelize/src/configs/test.json +1 -1
  153. package/lib/sequelize/src/http/auth.http +32 -0
  154. package/lib/sequelize/src/http/users.http +34 -0
  155. package/lib/sequelize/src/index.ts +1 -0
  156. package/lib/sequelize/src/middlewares/auth.middleware.ts +4 -4
  157. package/lib/sequelize/src/server.ts +1 -2
  158. package/lib/sequelize/src/services/auth.service.ts +5 -5
  159. package/lib/sequelize/src/services/users.service.ts +3 -3
  160. package/lib/sequelize/src/utils/logger.ts +5 -5
  161. package/lib/sequelize/tsconfig.json +2 -2
  162. package/lib/starter.js +5 -9
  163. package/lib/typeorm/.swcrc +39 -0
  164. package/lib/typeorm/Dockerfile +1 -1
  165. package/lib/typeorm/docker-compose.yml +1 -1
  166. package/lib/typeorm/ecosystem.config.js +42 -27
  167. package/lib/typeorm/nodemon.json +2 -2
  168. package/lib/typeorm/package.json +15 -8
  169. package/lib/typeorm/src/app.ts +1 -2
  170. package/lib/typeorm/src/configs/development.json +1 -1
  171. package/lib/typeorm/src/configs/production.json +1 -1
  172. package/lib/typeorm/src/configs/test.json +1 -1
  173. package/lib/typeorm/src/databases/index.ts +5 -5
  174. package/lib/typeorm/src/entities/users.entity.ts +26 -0
  175. package/lib/typeorm/src/http/auth.http +12 -15
  176. package/lib/typeorm/src/http/users.http +12 -16
  177. package/lib/typeorm/src/index.ts +1 -0
  178. package/lib/typeorm/src/middlewares/auth.middleware.ts +5 -9
  179. package/lib/typeorm/src/server.ts +1 -2
  180. package/lib/typeorm/src/services/auth.service.ts +13 -17
  181. package/lib/typeorm/src/services/users.service.ts +16 -22
  182. package/lib/typeorm/src/utils/logger.ts +5 -5
  183. package/lib/typeorm/tsconfig.json +3 -3
  184. package/package.json +13 -4
@@ -0,0 +1,78 @@
1
+ # baseURL
2
+ @baseURL = http://localhost:3000/graphql
3
+
4
+ ###
5
+ # Find All Users
6
+ POST {{ baseURL }}
7
+ Content-Type: application/json
8
+ X-REQUEST-TYPE: GraphQL
9
+
10
+ query {
11
+ getUsers {
12
+ id,
13
+ email,
14
+ password
15
+ }
16
+ }
17
+
18
+ ###
19
+ # Find User By Id
20
+ POST {{ baseURL }}
21
+ Content-Type: application/json
22
+ X-REQUEST-TYPE: GraphQL
23
+
24
+ query {
25
+ getUserById(userId: 1) {
26
+ id,
27
+ email,
28
+ password
29
+ }
30
+ }
31
+
32
+ ###
33
+ # Create User
34
+ POST {{ baseURL }}
35
+ Content-Type: application/json
36
+ X-REQUEST-TYPE: GraphQL
37
+
38
+ mutation {
39
+ createUser (userData: {
40
+ email: "example@email.com",
41
+ password: "password"
42
+ }) {
43
+ id,
44
+ email,
45
+ password
46
+ }
47
+ }
48
+
49
+ ###
50
+ # Modify User By Id
51
+ POST {{ baseURL }}
52
+ Content-Type: application/json
53
+ X-REQUEST-TYPE: GraphQL
54
+
55
+ mutation {
56
+ updateUser (userId: 1, userData: {
57
+ email: "example@email.com",
58
+ password: "password"
59
+ }) {
60
+ id,
61
+ email,
62
+ password
63
+ }
64
+ }
65
+
66
+ ###
67
+ # Delete User By Id
68
+ POST {{ baseURL }}
69
+ Content-Type: application/json
70
+ X-REQUEST-TYPE: GraphQL
71
+
72
+ mutation {
73
+ deleteUser (userId: 1) {
74
+ id,
75
+ email,
76
+ password
77
+ }
78
+ }
@@ -0,0 +1 @@
1
+ process.env['NODE_CONFIG_DIR'] = __dirname + '/configs';
@@ -0,0 +1,14 @@
1
+ import { User } from '@interfaces/users.interface';
2
+
3
+ export interface DataStoredInToken {
4
+ id: number;
5
+ }
6
+
7
+ export interface TokenData {
8
+ token: string;
9
+ expiresIn: number;
10
+ }
11
+
12
+ export interface RequestWithUser {
13
+ user: User;
14
+ }
@@ -0,0 +1,7 @@
1
+ export interface dbConfig {
2
+ host: string;
3
+ user: string;
4
+ port: number;
5
+ password: string;
6
+ database: string;
7
+ }
@@ -0,0 +1,5 @@
1
+ export interface User {
2
+ id: number;
3
+ email: string;
4
+ password: string;
5
+ }
@@ -0,0 +1,32 @@
1
+ import config from 'config';
2
+ import { verify } from 'jsonwebtoken';
3
+ import { AuthChecker } from 'type-graphql';
4
+ import { getRepository } from 'typeorm';
5
+ import { UserEntity } from '@entities/users.entity';
6
+ import { HttpException } from '@exceptions/HttpException';
7
+ import { RequestWithUser, DataStoredInToken } from '@interfaces/auth.interface';
8
+
9
+ export const authMiddleware = async req => {
10
+ try {
11
+ const Authorization = req.cookies['Authorization'] || (req.header('Authorization') ? req.header('Authorization').split('Bearer ')[1] : null);
12
+ if (Authorization) {
13
+ const secretKey: string = config.get('secretKey');
14
+ const { id } = (await verify(Authorization, secretKey)) as DataStoredInToken;
15
+ const userRepository = getRepository(UserEntity);
16
+ const findUser = await userRepository.findOne(id, { select: ['id', 'email', 'password'] });
17
+ return findUser;
18
+ }
19
+
20
+ return null;
21
+ } catch (error) {
22
+ throw new HttpException(401, 'Wrong authentication token');
23
+ }
24
+ };
25
+
26
+ export const authChecker: AuthChecker<RequestWithUser> = async ({ context: { user } }) => {
27
+ if (!user) {
28
+ throw new HttpException(404, 'Authentication token missing');
29
+ }
30
+
31
+ return true;
32
+ };
@@ -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;
@@ -0,0 +1,61 @@
1
+ import { hash, compare } from 'bcrypt';
2
+ import config from 'config';
3
+ import { sign } from 'jsonwebtoken';
4
+ import { EntityRepository } from 'typeorm';
5
+ import { CreateUserDto } from '@dtos/users.dto';
6
+ import { UserEntity } from '@entities/users.entity';
7
+ import { HttpException } from '@exceptions/HttpException';
8
+ import { DataStoredInToken, TokenData } from '@interfaces/auth.interface';
9
+ import { User } from '@interfaces/users.interface';
10
+ import { isEmpty } from '@utils/util';
11
+
12
+ @EntityRepository(UserEntity)
13
+ export default class AuthRepository {
14
+ public async userSignUp(userData: CreateUserDto): Promise<User> {
15
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
16
+
17
+ const findUser: User = await UserEntity.findOne({ where: { email: userData.email } });
18
+ if (findUser) throw new HttpException(409, `You're email ${userData.email} already exists`);
19
+
20
+ const hashedPassword = await hash(userData.password, 10);
21
+ const createUserData: User = await UserEntity.save({ ...userData, password: hashedPassword });
22
+
23
+ return createUserData;
24
+ }
25
+
26
+ public async userLogIn(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 UserEntity.findOne({ where: { 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 userLogOut(userId: number): Promise<User> {
42
+ if (isEmpty(userId)) throw new HttpException(400, "You're not userId");
43
+
44
+ const findUser: User = await UserEntity.findOne({ where: { id: userId } });
45
+ if (!findUser) throw new HttpException(409, "You're not user");
46
+
47
+ return findUser;
48
+ }
49
+
50
+ public createToken(user: User): TokenData {
51
+ const dataStoredInToken: DataStoredInToken = { id: user.id };
52
+ const secretKey: string = config.get('secretKey');
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
+ }
@@ -0,0 +1,60 @@
1
+ import { hash } from 'bcrypt';
2
+ import { EntityRepository } from 'typeorm';
3
+ import { CreateUserDto } from '@dtos/users.dto';
4
+ import { UserEntity } from '@entities/users.entity';
5
+ import { HttpException } from '@exceptions/HttpException';
6
+ import { User } from '@interfaces/users.interface';
7
+ import { isEmpty } from '@utils/util';
8
+
9
+ @EntityRepository()
10
+ export default class UserRepository {
11
+ public async userFindAll(): Promise<User[]> {
12
+ const users: User[] = await UserEntity.find();
13
+
14
+ return users;
15
+ }
16
+
17
+ public async userFindById(userId: number): Promise<User> {
18
+ if (isEmpty(userId)) throw new HttpException(400, "You're not userId");
19
+
20
+ const user: User = await UserEntity.findOne({ where: { id: userId } });
21
+ if (!user) throw new HttpException(409, "You're not user");
22
+
23
+ return user;
24
+ }
25
+
26
+ public async userCreate(userData: CreateUserDto): Promise<User> {
27
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
28
+
29
+ const findUser: User = await UserEntity.findOne({ where: { email: userData.email } });
30
+ if (findUser) throw new HttpException(409, `You're email ${userData.email} already exists`);
31
+
32
+ const hashedPassword = await hash(userData.password, 10);
33
+ const createUserData: User = await UserEntity.save({ ...userData, password: hashedPassword });
34
+
35
+ return createUserData;
36
+ }
37
+
38
+ public async userUpdate(userId: number, userData: CreateUserDto): Promise<User> {
39
+ if (isEmpty(userData)) throw new HttpException(400, "You're not userData");
40
+
41
+ const findUser: User = await UserEntity.findOne({ where: { id: userId } });
42
+ if (!findUser) throw new HttpException(409, "You're not user");
43
+
44
+ const hashedPassword = await hash(userData.password, 10);
45
+ await UserEntity.update(userId, { ...userData, password: hashedPassword });
46
+
47
+ const updateUser: User = await UserEntity.findOne({ where: { id: userId } });
48
+ return updateUser;
49
+ }
50
+
51
+ public async userDelete(userId: number): Promise<User> {
52
+ if (isEmpty(userId)) throw new HttpException(400, "You're not userId");
53
+
54
+ const findUser: User = await UserEntity.findOne({ where: { id: userId } });
55
+ if (!findUser) throw new HttpException(409, "You're not user");
56
+
57
+ await UserEntity.delete({ id: userId });
58
+ return findUser;
59
+ }
60
+ }
@@ -0,0 +1,32 @@
1
+ import { Authorized, Arg, Ctx, Mutation, Resolver } from 'type-graphql';
2
+ import { CreateUserDto } from '@dtos/users.dto';
3
+ import AuthRepository from '@repositories/auth.repository';
4
+ import { User } from '@typedefs/users.type';
5
+
6
+ @Resolver()
7
+ export class authResolver extends AuthRepository {
8
+ @Mutation(() => User, {
9
+ description: 'User signup',
10
+ })
11
+ async signup(@Arg('userData') userData: CreateUserDto): Promise<User> {
12
+ const user: User = await this.userSignUp(userData);
13
+ return user;
14
+ }
15
+
16
+ @Mutation(() => User, {
17
+ description: 'User login',
18
+ })
19
+ async login(@Arg('userData') userData: CreateUserDto): Promise<User> {
20
+ const { findUser } = await this.userLogIn(userData);
21
+ return findUser;
22
+ }
23
+
24
+ @Authorized()
25
+ @Mutation(() => User, {
26
+ description: 'User logout',
27
+ })
28
+ async logout(@Ctx('user') userData: any): Promise<User> {
29
+ const user = await this.userLogOut(userData);
30
+ return user;
31
+ }
32
+ }
@@ -0,0 +1,47 @@
1
+ import { Arg, Mutation, Query, Resolver } from 'type-graphql';
2
+ import { CreateUserDto } from '@dtos/users.dto';
3
+ import UserRepository from '@repositories/users.repository';
4
+ import { User } from '@typedefs/users.type';
5
+
6
+ @Resolver()
7
+ export class userResolver extends UserRepository {
8
+ @Query(() => [User], {
9
+ description: 'User find list',
10
+ })
11
+ async getUsers(): Promise<User[]> {
12
+ const users: User[] = await this.userFindAll();
13
+ return users;
14
+ }
15
+
16
+ @Query(() => User, {
17
+ description: 'User find by id',
18
+ })
19
+ async getUserById(@Arg('userId') userId: number): Promise<User> {
20
+ const user: User = await this.userFindById(userId);
21
+ return user;
22
+ }
23
+
24
+ @Mutation(() => User, {
25
+ description: 'User create',
26
+ })
27
+ async createUser(@Arg('userData') userData: CreateUserDto): Promise<User> {
28
+ const user: User = await this.userCreate(userData);
29
+ return user;
30
+ }
31
+
32
+ @Mutation(() => User, {
33
+ description: 'User update',
34
+ })
35
+ async updateUser(@Arg('userId') userId: number, @Arg('userData') userData: CreateUserDto): Promise<User> {
36
+ const user: User = await this.userUpdate(userId, userData);
37
+ return user;
38
+ }
39
+
40
+ @Mutation(() => User, {
41
+ description: 'User delete',
42
+ })
43
+ async deleteUser(@Arg('userId') userId: number): Promise<User> {
44
+ const user: User = await this.userDelete(userId);
45
+ return user;
46
+ }
47
+ }
@@ -0,0 +1,14 @@
1
+ import 'reflect-metadata';
2
+ import 'dotenv/config';
3
+ import '@/index';
4
+ import App from '@/app';
5
+ import validateEnv from '@utils/validateEnv';
6
+
7
+ import { authResolver } from '@resolvers/auth.resolver';
8
+ import { userResolver } from '@resolvers/users.resolver';
9
+
10
+ validateEnv();
11
+
12
+ const app = new App([authResolver, userResolver]);
13
+
14
+ app.listen();
@@ -0,0 +1,52 @@
1
+ import request from 'supertest';
2
+ import App from '@/app';
3
+ import { CreateUserDto } from '@dtos/users.dto';
4
+ import AuthRoute from '@routes/auth.route';
5
+
6
+ afterAll(async () => {
7
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
8
+ });
9
+
10
+ describe('Testing Auth', () => {
11
+ describe('[POST] /signup', () => {
12
+ it('response should have the Create userData', () => {
13
+ const userData: CreateUserDto = {
14
+ email: 'test@email.com',
15
+ password: 'q1w2e3r4',
16
+ };
17
+ const authRoute = new AuthRoute();
18
+ const app = new App([authRoute]);
19
+
20
+ return request(app.getServer()).post('/signup').send(userData);
21
+ });
22
+ });
23
+
24
+ describe('[POST] /login', () => {
25
+ it('response should have the Set-Cookie header with the Authorization token', async () => {
26
+ const userData: CreateUserDto = {
27
+ email: 'test@email.com',
28
+ password: 'q1w2e3r4',
29
+ };
30
+
31
+ const authRoute = new AuthRoute();
32
+ const app = new App([authRoute]);
33
+
34
+ return request(app.getServer())
35
+ .post('/login')
36
+ .send(userData)
37
+ .expect('Set-Cookie', /^Authorization=.+/);
38
+ });
39
+ });
40
+
41
+ // error: StatusCode : 404, Message : Authentication token missing
42
+ // describe('[POST] /logout', () => {
43
+ // it('logout Set-Cookie Authorization=; Max-age=0', () => {
44
+ // const authRoute = new AuthRoute();
45
+ // const app = new App([authRoute]);
46
+
47
+ // return request(app.getServer())
48
+ // .post('/logout')
49
+ // .expect('Set-Cookie', /^Authorization=\;/);
50
+ // });
51
+ // });
52
+ });
@@ -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,71 @@
1
+ import request from 'supertest';
2
+ import App from '@app';
3
+ import { CreateUserDto } from '@dtos/users.dto';
4
+ import { User } from '@interfaces/users.interface';
5
+ import userModel from '@models/users.model';
6
+ import UserRoute from '@routes/users.route';
7
+
8
+ afterAll(async () => {
9
+ await new Promise<void>(resolve => setTimeout(() => resolve(), 500));
10
+ });
11
+
12
+ describe('Testing Users', () => {
13
+ describe('[GET] /users', () => {
14
+ it('response statusCode 200 / findAll', () => {
15
+ const findUser: User[] = userModel;
16
+ const usersRoute = new UserRoute();
17
+ const app = new App([usersRoute]);
18
+
19
+ return request(app.getServer()).get(`${usersRoute.path}`).expect(200, { data: findUser, message: 'findAll' });
20
+ });
21
+ });
22
+
23
+ describe('[GET] /users/:id', () => {
24
+ it('response statusCode 200 / findOne', () => {
25
+ const userId = 1;
26
+ const findUser: User = userModel.find(user => user.id === userId);
27
+ const usersRoute = new UserRoute();
28
+ const app = new App([usersRoute]);
29
+
30
+ return request(app.getServer()).get(`${usersRoute.path}/${userId}`).expect(200, { data: findUser, message: 'findOne' });
31
+ });
32
+ });
33
+
34
+ describe('[POST] /users', () => {
35
+ it('response statusCode 201 / created', async () => {
36
+ const userData: CreateUserDto = {
37
+ email: 'test@email.com',
38
+ password: 'q1w2e3r4',
39
+ };
40
+ const usersRoute = new UserRoute();
41
+ const app = new App([usersRoute]);
42
+
43
+ return request(app.getServer()).post(`${usersRoute.path}`).send(userData).expect(201);
44
+ });
45
+ });
46
+
47
+ describe('[PUT] /users/:id', () => {
48
+ it('response statusCode 200 / updated', async () => {
49
+ const userId = 1;
50
+ const userData: CreateUserDto = {
51
+ email: 'test@email.com',
52
+ password: 'q1w2e3r4',
53
+ };
54
+ const usersRoute = new UserRoute();
55
+ const app = new App([usersRoute]);
56
+
57
+ return request(app.getServer()).put(`${usersRoute.path}/${userId}`).send(userData).expect(200);
58
+ });
59
+ });
60
+
61
+ describe('[DELETE] /users/:id', () => {
62
+ it('response statusCode 200 / deleted', () => {
63
+ const userId = 1;
64
+ const deleteUser: User[] = userModel.filter(user => user.id !== userId);
65
+ const usersRoute = new UserRoute();
66
+ const app = new App([usersRoute]);
67
+
68
+ return request(app.getServer()).delete(`${usersRoute.path}/${userId}`).expect(200, { data: deleteUser, message: 'deleted' });
69
+ });
70
+ });
71
+ });
@@ -0,0 +1,13 @@
1
+ import { Field, ObjectType } from 'type-graphql';
2
+
3
+ @ObjectType()
4
+ export class User {
5
+ @Field()
6
+ id: number;
7
+
8
+ @Field()
9
+ email: string;
10
+
11
+ @Field()
12
+ password: string;
13
+ }
@@ -0,0 +1,75 @@
1
+ import config from 'config';
2
+ import { existsSync, mkdirSync } from 'fs';
3
+ import { join } from 'path';
4
+ import winston from 'winston';
5
+ import winstonDaily from 'winston-daily-rotate-file';
6
+
7
+ // logs dir
8
+ const logDir: string = join(__dirname, config.get('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
+ export 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
+ export const responseLogger = request => {
60
+ const { query } = request.request;
61
+ logger.info(query);
62
+ };
63
+
64
+ export const errorLogger = error => {
65
+ const { validationErrors } = error.extensions.exception;
66
+
67
+ let message = '';
68
+ if (validationErrors) {
69
+ message = validationErrors.map(error => Object.values(error.constraints)).join(', ');
70
+ } else {
71
+ message = error.message;
72
+ }
73
+
74
+ logger.error(message);
75
+ };
@@ -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;