nodejs-quickstart-structure 1.18.1 → 1.19.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 (104) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +2 -1
  3. package/lib/modules/caching-setup.js +76 -73
  4. package/lib/modules/kafka-setup.js +249 -191
  5. package/lib/modules/project-setup.js +1 -0
  6. package/package.json +13 -2
  7. package/templates/clean-architecture/js/src/errors/BadRequestError.js +11 -10
  8. package/templates/clean-architecture/js/src/errors/BadRequestError.spec.js.ejs +22 -21
  9. package/templates/clean-architecture/js/src/errors/NotFoundError.js +11 -10
  10. package/templates/clean-architecture/js/src/errors/NotFoundError.spec.js.ejs +22 -21
  11. package/templates/clean-architecture/js/src/infrastructure/repositories/UserRepository.js.ejs +69 -39
  12. package/templates/clean-architecture/js/src/infrastructure/repositories/UserRepository.spec.js.ejs +142 -81
  13. package/templates/clean-architecture/js/src/interfaces/controllers/userController.js.ejs +156 -75
  14. package/templates/clean-architecture/js/src/interfaces/controllers/userController.spec.js.ejs +234 -138
  15. package/templates/clean-architecture/js/src/interfaces/graphql/resolvers/user.resolvers.js.ejs +27 -21
  16. package/templates/clean-architecture/js/src/interfaces/graphql/resolvers/user.resolvers.spec.js.ejs +66 -49
  17. package/templates/clean-architecture/js/src/interfaces/graphql/typeDefs/user.types.js.ejs +19 -17
  18. package/templates/clean-architecture/js/src/interfaces/routes/api.js +12 -10
  19. package/templates/clean-architecture/js/src/usecases/DeleteUser.js +11 -0
  20. package/templates/clean-architecture/js/src/usecases/DeleteUser.spec.js.ejs +47 -0
  21. package/templates/clean-architecture/js/src/usecases/UpdateUser.js +11 -0
  22. package/templates/clean-architecture/js/src/usecases/UpdateUser.spec.js.ejs +48 -0
  23. package/templates/clean-architecture/js/src/utils/errorMessages.js +14 -0
  24. package/templates/clean-architecture/ts/src/errors/BadRequestError.spec.ts.ejs +22 -21
  25. package/templates/clean-architecture/ts/src/errors/BadRequestError.ts +9 -8
  26. package/templates/clean-architecture/ts/src/errors/NotFoundError.spec.ts.ejs +22 -21
  27. package/templates/clean-architecture/ts/src/errors/NotFoundError.ts +9 -8
  28. package/templates/clean-architecture/ts/src/infrastructure/repositories/UserRepository.spec.ts.ejs +175 -85
  29. package/templates/clean-architecture/ts/src/infrastructure/repositories/userRepository.ts.ejs +74 -0
  30. package/templates/clean-architecture/ts/src/interfaces/controllers/userController.spec.ts.ejs +331 -185
  31. package/templates/clean-architecture/ts/src/interfaces/controllers/userController.ts.ejs +173 -84
  32. package/templates/clean-architecture/ts/src/interfaces/graphql/resolvers/user.resolvers.spec.ts.ejs +68 -51
  33. package/templates/clean-architecture/ts/src/interfaces/graphql/resolvers/user.resolvers.ts.ejs +29 -21
  34. package/templates/clean-architecture/ts/src/interfaces/graphql/typeDefs/user.types.ts.ejs +17 -15
  35. package/templates/clean-architecture/ts/src/interfaces/routes/userRoutes.ts +13 -11
  36. package/templates/clean-architecture/ts/src/usecases/deleteUser.spec.ts.ejs +47 -0
  37. package/templates/clean-architecture/ts/src/usecases/deleteUser.ts +9 -0
  38. package/templates/clean-architecture/ts/src/usecases/updateUser.spec.ts.ejs +48 -0
  39. package/templates/clean-architecture/ts/src/usecases/updateUser.ts +9 -0
  40. package/templates/clean-architecture/ts/src/utils/errorMessages.ts +12 -0
  41. package/templates/common/.gitattributes +46 -0
  42. package/templates/common/README.md.ejs +294 -270
  43. package/templates/common/caching/clean/js/DeleteUser.js.ejs +27 -0
  44. package/templates/common/caching/clean/js/UpdateUser.js.ejs +27 -0
  45. package/templates/common/caching/clean/ts/deleteUser.ts.ejs +24 -0
  46. package/templates/common/caching/clean/ts/updateUser.ts.ejs +25 -0
  47. package/templates/common/caching/ts/memoryCache.ts.ejs +73 -64
  48. package/templates/common/caching/ts/redisClient.ts.ejs +89 -80
  49. package/templates/common/database/js/models/User.js.ejs +79 -53
  50. package/templates/common/database/js/models/User.js.mongoose.ejs +23 -19
  51. package/templates/common/database/js/models/User.spec.js.ejs +94 -84
  52. package/templates/common/database/ts/models/User.spec.ts.ejs +100 -84
  53. package/templates/common/database/ts/models/User.ts.ejs +87 -61
  54. package/templates/common/database/ts/models/User.ts.mongoose.ejs +30 -25
  55. package/templates/common/health/js/healthRoute.js.ejs +50 -47
  56. package/templates/common/health/ts/healthRoute.ts.ejs +49 -46
  57. package/templates/common/jest.e2e.config.js.ejs +8 -8
  58. package/templates/common/kafka/js/messaging/baseConsumer.js.ejs +30 -30
  59. package/templates/common/kafka/js/messaging/userEventSchema.js.ejs +12 -11
  60. package/templates/common/kafka/js/messaging/welcomeEmailConsumer.js.ejs +44 -31
  61. package/templates/common/kafka/js/messaging/welcomeEmailConsumer.spec.js.ejs +86 -49
  62. package/templates/common/kafka/js/services/kafkaService.js.ejs +93 -93
  63. package/templates/common/kafka/js/utils/kafkaEvents.js.ejs +7 -0
  64. package/templates/common/kafka/ts/messaging/userEventSchema.spec.ts.ejs +51 -51
  65. package/templates/common/kafka/ts/messaging/userEventSchema.ts.ejs +12 -11
  66. package/templates/common/kafka/ts/messaging/welcomeEmailConsumer.spec.ts.ejs +86 -49
  67. package/templates/common/kafka/ts/messaging/welcomeEmailConsumer.ts.ejs +38 -25
  68. package/templates/common/kafka/ts/services/kafkaService.ts.ejs +95 -95
  69. package/templates/common/kafka/ts/utils/kafkaEvents.ts.ejs +5 -0
  70. package/templates/common/shutdown/js/gracefulShutdown.js.ejs +65 -61
  71. package/templates/common/shutdown/js/gracefulShutdown.spec.js.ejs +149 -160
  72. package/templates/common/shutdown/ts/gracefulShutdown.spec.ts.ejs +179 -158
  73. package/templates/common/shutdown/ts/gracefulShutdown.ts.ejs +59 -55
  74. package/templates/common/src/tests/e2e/e2e.users.test.js.ejs +120 -49
  75. package/templates/common/src/tests/e2e/e2e.users.test.ts.ejs +120 -49
  76. package/templates/common/swagger.yml.ejs +118 -66
  77. package/templates/db/mysql/V1__Initial_Setup.sql.ejs +10 -9
  78. package/templates/db/postgres/V1__Initial_Setup.sql.ejs +10 -9
  79. package/templates/mvc/js/src/controllers/userController.js.ejs +246 -105
  80. package/templates/mvc/js/src/controllers/userController.spec.js.ejs +481 -209
  81. package/templates/mvc/js/src/errors/BadRequestError.js +11 -10
  82. package/templates/mvc/js/src/errors/BadRequestError.spec.js.ejs +22 -21
  83. package/templates/mvc/js/src/errors/NotFoundError.js +11 -10
  84. package/templates/mvc/js/src/errors/NotFoundError.spec.js.ejs +22 -21
  85. package/templates/mvc/js/src/graphql/resolvers/user.resolvers.js.ejs +25 -19
  86. package/templates/mvc/js/src/graphql/resolvers/user.resolvers.spec.js.ejs +64 -47
  87. package/templates/mvc/js/src/graphql/typeDefs/user.types.js.ejs +19 -17
  88. package/templates/mvc/js/src/routes/api.js +10 -8
  89. package/templates/mvc/js/src/routes/api.spec.js.ejs +41 -36
  90. package/templates/mvc/js/src/utils/errorMessages.js +14 -0
  91. package/templates/mvc/ts/src/controllers/userController.spec.ts.ejs +481 -203
  92. package/templates/mvc/ts/src/controllers/userController.ts.ejs +248 -107
  93. package/templates/mvc/ts/src/errors/BadRequestError.spec.ts.ejs +22 -21
  94. package/templates/mvc/ts/src/errors/BadRequestError.ts +9 -8
  95. package/templates/mvc/ts/src/errors/NotFoundError.spec.ts.ejs +27 -21
  96. package/templates/mvc/ts/src/errors/NotFoundError.ts +9 -8
  97. package/templates/mvc/ts/src/graphql/resolvers/user.resolvers.spec.ts.ejs +68 -51
  98. package/templates/mvc/ts/src/graphql/resolvers/user.resolvers.ts.ejs +29 -21
  99. package/templates/mvc/ts/src/graphql/typeDefs/user.types.ts.ejs +17 -15
  100. package/templates/mvc/ts/src/index.ts.ejs +156 -153
  101. package/templates/mvc/ts/src/routes/api.spec.ts.ejs +59 -40
  102. package/templates/mvc/ts/src/routes/api.ts +12 -10
  103. package/templates/mvc/ts/src/utils/errorMessages.ts +12 -0
  104. package/templates/clean-architecture/ts/src/infrastructure/repositories/UserRepository.ts.ejs +0 -37
@@ -1,84 +1,173 @@
1
- <% if (communication !== 'GraphQL') { -%>
2
- import { Request, Response, NextFunction } from 'express';
3
- import { HTTP_STATUS } from '@/utils/httpCodes';
4
- <% } -%>
5
- import { UserRepository } from '@/infrastructure/repositories/UserRepository';
6
- import CreateUser from '@/usecases/createUser';
7
- import GetAllUsers from '@/usecases/getAllUsers';
8
- import logger from '@/infrastructure/log/logger';
9
- <%_ if (communication === 'Kafka') { -%>
10
- import { kafkaService } from '@/infrastructure/messaging/kafkaClient';
11
- <%_ } -%>
12
-
13
- export class UserController {
14
- private createUserUseCase: CreateUser;
15
- private getAllUsersUseCase: GetAllUsers;
16
-
17
- constructor() {
18
- const userRepository = new UserRepository();
19
- this.createUserUseCase = new CreateUser(userRepository);
20
- this.getAllUsersUseCase = new GetAllUsers(userRepository);
21
- }
22
-
23
- <% if (communication === 'GraphQL') { -%>
24
- async createUser(data: { name: string, email: string }) {
25
- try {
26
- const { name, email } = data;
27
- const user = await this.createUserUseCase.execute(name, email);
28
- <%_ if (communication === 'Kafka') { -%>
29
- await kafkaService.sendMessage('user-topic', JSON.stringify({
30
- action: 'USER_CREATED',
31
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
- payload: { id: (user as any).id || (user as any)._id, email: user.email }
33
- }));
34
- <%_ } -%>
35
- return user;
36
- } catch (error: unknown) {
37
- const message = error instanceof Error ? error.message : 'Unknown error';
38
- logger.error('UserController CreateUser Error:', message);
39
- throw error;
40
- }
41
- }
42
-
43
- async getUsers() {
44
- try {
45
- const users = await this.getAllUsersUseCase.execute();
46
- return users;
47
- } catch (error: unknown) {
48
- const message = error instanceof Error ? error.message : 'Unknown error';
49
- logger.error('UserController GetUsers Error:', message);
50
- throw error;
51
- }
52
- }
53
- <% } else { -%>
54
- async createUser(req: Request, res: Response, next: NextFunction) {
55
- try {
56
- const { name, email } = req.body;
57
- const user = await this.createUserUseCase.execute(name, email);
58
- <%_ if (communication === 'Kafka') { -%>
59
- await kafkaService.sendMessage('user-topic', JSON.stringify({
60
- action: 'USER_CREATED',
61
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
62
- payload: { id: (user as any).id || (user as any)._id, email: user.email }
63
- }));
64
- <%_ } -%>
65
- res.status(HTTP_STATUS.CREATED).json(user);
66
- } catch (error: unknown) {
67
- const message = error instanceof Error ? error.message : 'Unknown error';
68
- logger.error('UserController CreateUser Error:', message);
69
- next(error);
70
- }
71
- }
72
-
73
- async getUsers(req: Request, res: Response, next: NextFunction) {
74
- try {
75
- const users = await this.getAllUsersUseCase.execute();
76
- res.json(users);
77
- } catch (error: unknown) {
78
- const message = error instanceof Error ? error.message : 'Unknown error';
79
- logger.error('UserController GetUsers Error:', message);
80
- next(error);
81
- }
82
- }
83
- <% } -%>
84
- }
1
+ import { ERROR_MESSAGES } from '@/utils/errorMessages';
2
+ <% if (communication !== 'GraphQL') { -%>
3
+ import { Request, Response, NextFunction } from 'express';
4
+ import { HTTP_STATUS } from '@/utils/httpCodes';
5
+ <% } -%>
6
+ import { UserRepository } from '@/infrastructure/repositories/UserRepository';
7
+ import CreateUser from '@/usecases/createUser';
8
+ import GetAllUsers from '@/usecases/getAllUsers';
9
+ import UpdateUser from '@/usecases/updateUser';
10
+ import DeleteUser from '@/usecases/deleteUser';
11
+ import logger from '@/infrastructure/log/logger';
12
+ <%_ if (communication === 'Kafka') { -%>
13
+ import { kafkaService } from '@/infrastructure/messaging/kafkaClient';
14
+ import { KAFKA_ACTIONS } from '@/utils/kafkaEvents';
15
+ <%_ } -%>
16
+
17
+ export class UserController {
18
+ private createUserUseCase: CreateUser;
19
+ private getAllUsersUseCase: GetAllUsers;
20
+ private updateUserUseCase: UpdateUser;
21
+ private deleteUserUseCase: DeleteUser;
22
+
23
+ constructor() {
24
+ const userRepository = new UserRepository();
25
+ this.createUserUseCase = new CreateUser(userRepository);
26
+ this.getAllUsersUseCase = new GetAllUsers(userRepository);
27
+ this.updateUserUseCase = new UpdateUser(userRepository);
28
+ this.deleteUserUseCase = new DeleteUser(userRepository);
29
+ }
30
+
31
+ <% if (communication === 'GraphQL') { -%>
32
+ async createUser(data: { name: string, email: string }) {
33
+ try {
34
+ const { name, email } = data;
35
+ const user = await this.createUserUseCase.execute(name, email);
36
+ <%_ if (communication === 'Kafka') { -%>
37
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
+ const userId = (user as any).id || (user as any)._id;
39
+ await kafkaService.sendMessage('user-topic', JSON.stringify({
40
+ action: KAFKA_ACTIONS.USER_CREATED,
41
+ payload: { id: userId, email: user.email }
42
+ }), userId?.toString() || '');
43
+ <%_ } -%>
44
+ return user;
45
+ } catch (error: unknown) {
46
+ const message = error instanceof Error ? error.message : 'Unknown error';
47
+ logger.error(`${ERROR_MESSAGES.CREATE_USER_ERROR}:`, message);
48
+ throw error;
49
+ }
50
+ }
51
+
52
+ async getUsers() {
53
+ try {
54
+ const users = await this.getAllUsersUseCase.execute();
55
+ return users;
56
+ } catch (error: unknown) {
57
+ const message = error instanceof Error ? error.message : 'Unknown error';
58
+ logger.error(`${ERROR_MESSAGES.FETCH_USERS_ERROR}:`, message);
59
+ throw error;
60
+ }
61
+ }
62
+
63
+ async updateUser(id: string, data: { name?: string, email?: string }) {
64
+ try {
65
+ const user = await this.updateUserUseCase.execute(id, data);
66
+ if (!user) throw new Error(ERROR_MESSAGES.USER_NOT_FOUND);
67
+ <%_ if (communication === 'Kafka') { -%>
68
+ await kafkaService.sendMessage('user-topic', JSON.stringify({
69
+ action: KAFKA_ACTIONS.USER_UPDATED,
70
+ payload: { id, email: user.email }
71
+ }), id);
72
+ <%_ } -%>
73
+ return user;
74
+ } catch (error: unknown) {
75
+ const message = error instanceof Error ? error.message : 'Unknown error';
76
+ logger.error(`${ERROR_MESSAGES.UPDATE_USER_ERROR}:`, message);
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ async deleteUser(id: string) {
82
+ try {
83
+ const deleted = await this.deleteUserUseCase.execute(id);
84
+ if (!deleted) throw new Error(ERROR_MESSAGES.USER_NOT_FOUND);
85
+ <%_ if (communication === 'Kafka') { -%>
86
+ await kafkaService.sendMessage('user-topic', JSON.stringify({
87
+ action: KAFKA_ACTIONS.USER_DELETED,
88
+ payload: { id }
89
+ }), id);
90
+ <%_ } -%>
91
+ return true;
92
+ } catch (error: unknown) {
93
+ const message = error instanceof Error ? error.message : 'Unknown error';
94
+ logger.error(`${ERROR_MESSAGES.DELETE_USER_ERROR}:`, message);
95
+ throw error;
96
+ }
97
+ }
98
+ <% } else { -%>
99
+ async createUser(req: Request, res: Response, next: NextFunction) {
100
+ try {
101
+ const { name, email } = req.body || {};
102
+ const user = await this.createUserUseCase.execute(name, email);
103
+ <%_ if (communication === 'Kafka') { -%>
104
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
105
+ const userId = (user as any).id || (user as any)._id;
106
+ await kafkaService.sendMessage('user-topic', JSON.stringify({
107
+ action: KAFKA_ACTIONS.USER_CREATED,
108
+ payload: { id: userId, email: user.email }
109
+ }), userId?.toString() || '');
110
+ <%_ } -%>
111
+ res.status(HTTP_STATUS.CREATED).json(user);
112
+ } catch (error: unknown) {
113
+ const message = error instanceof Error ? error.message : 'Unknown error';
114
+ logger.error(`${ERROR_MESSAGES.CREATE_USER_ERROR}:`, message);
115
+ next(error);
116
+ }
117
+ }
118
+
119
+ async getUsers(req: Request, res: Response, next: NextFunction) {
120
+ try {
121
+ const users = await this.getAllUsersUseCase.execute();
122
+ res.json(users);
123
+ } catch (error: unknown) {
124
+ const message = error instanceof Error ? error.message : 'Unknown error';
125
+ logger.error(`${ERROR_MESSAGES.FETCH_USERS_ERROR}:`, message);
126
+ next(error);
127
+ }
128
+ }
129
+
130
+ async updateUser(req: Request, res: Response, next: NextFunction) {
131
+ try {
132
+ const { id } = req.params;
133
+ const { name, email } = req.body || {};
134
+ const user = await this.updateUserUseCase.execute(id, { name, email });
135
+ if (!user) {
136
+ return res.status(HTTP_STATUS.NOT_FOUND).json({ error: ERROR_MESSAGES.USER_NOT_FOUND });
137
+ }
138
+ <%_ if (communication === 'Kafka') { -%>
139
+ await kafkaService.sendMessage('user-topic', JSON.stringify({
140
+ action: KAFKA_ACTIONS.USER_UPDATED,
141
+ payload: { id, email: user.email }
142
+ }), id);
143
+ <%_ } -%>
144
+ res.json(user);
145
+ } catch (error: unknown) {
146
+ const message = error instanceof Error ? error.message : 'Unknown error';
147
+ logger.error(`${ERROR_MESSAGES.UPDATE_USER_ERROR}:`, message);
148
+ next(error);
149
+ }
150
+ }
151
+
152
+ async deleteUser(req: Request, res: Response, next: NextFunction) {
153
+ try {
154
+ const { id } = req.params;
155
+ const deleted = await this.deleteUserUseCase.execute(id);
156
+ if (!deleted) {
157
+ return res.status(HTTP_STATUS.NOT_FOUND).json({ error: ERROR_MESSAGES.USER_NOT_FOUND });
158
+ }
159
+ <%_ if (communication === 'Kafka') { -%>
160
+ await kafkaService.sendMessage('user-topic', JSON.stringify({
161
+ action: KAFKA_ACTIONS.USER_DELETED,
162
+ payload: { id }
163
+ }), id);
164
+ <%_ } -%>
165
+ res.status(HTTP_STATUS.OK).json({ message: 'User deleted successfully' });
166
+ } catch (error: unknown) {
167
+ const message = error instanceof Error ? error.message : 'Unknown error';
168
+ logger.error(`${ERROR_MESSAGES.DELETE_USER_ERROR}:`, message);
169
+ next(error);
170
+ }
171
+ }
172
+ <% } -%>
173
+ }
@@ -1,51 +1,68 @@
1
- import { userResolvers } from '@/interfaces/graphql/resolvers/user.resolvers';
2
-
3
- const mockGetUsers = jest.fn().mockResolvedValue([{ id: '1', name: 'John Doe', email: 'john@example.com' }]);
4
- const mockCreateUser = jest.fn().mockResolvedValue({ id: '1', name: 'Jane', email: 'jane@example.com' });
5
-
6
- jest.mock('@/interfaces/controllers/userController', () => {
7
- return {
8
- UserController: jest.fn().mockImplementation(() => ({
9
- getUsers: (...args: unknown[]) => mockGetUsers(...args),
10
- createUser: (...args: unknown[]) => mockCreateUser(...args)
11
- }))
12
- };
13
- });
14
-
15
- describe('User Resolvers', () => {
16
- afterEach(() => {
17
- jest.clearAllMocks();
18
- });
19
-
20
- describe('Query.getAllUsers', () => {
21
- it('should return all users', async () => {
22
- const result = await userResolvers.Query.getAllUsers();
23
- expect(result).toEqual([{ id: '1', name: 'John Doe', email: 'john@example.com' }]);
24
- expect(mockGetUsers).toHaveBeenCalledTimes(1);
25
- });
26
- });
27
-
28
- describe('Mutation.createUser', () => {
29
- it('should create and return a new user', async () => {
30
- const result = await userResolvers.Mutation.createUser(null, { name: 'Jane', email: 'jane@example.com' });
31
- expect(result).toEqual({ id: '1', name: 'Jane', email: 'jane@example.com' });
32
- expect(mockCreateUser).toHaveBeenCalledWith({ name: 'Jane', email: 'jane@example.com' });
33
- expect(mockCreateUser).toHaveBeenCalledTimes(1);
34
- });
35
- });
36
- <%_ if (database === 'MongoDB') { -%>
37
- describe('User.id', () => {
38
- it('should return parent.id if available', () => {
39
- const parent = { id: '123' };
40
- const result = userResolvers.User.id(parent as { id?: string; _id?: unknown });
41
- expect(result).toBe('123');
42
- });
43
-
44
- it('should fallback to parent._id if id is not available', () => {
45
- const parent = { _id: '456' };
46
- const result = userResolvers.User.id(parent as { id?: string; _id?: unknown });
47
- expect(result).toBe('456');
48
- });
49
- });
50
- <%_ } -%>
51
- });
1
+ import { userResolvers } from '@/interfaces/graphql/resolvers/user.resolvers';
2
+
3
+ const mockGetUsers = jest.fn().mockResolvedValue([{ id: '1', name: 'John Doe', email: 'john@example.com' }]);
4
+ const mockCreateUser = jest.fn().mockResolvedValue({ id: '1', name: 'Jane', email: 'jane@example.com' });
5
+
6
+ jest.mock('@/interfaces/controllers/userController', () => {
7
+ return {
8
+ UserController: jest.fn().mockImplementation(() => ({
9
+ getUsers: (...args: unknown[]) => mockGetUsers(...args),
10
+ createUser: (...args: unknown[]) => mockCreateUser(...args),
11
+ updateUser: jest.fn().mockImplementation((id, data) => Promise.resolve({ id, ...data })),
12
+ deleteUser: jest.fn().mockImplementation(() => Promise.resolve(true))
13
+ }))
14
+ };
15
+ });
16
+
17
+ describe('User Resolvers', () => {
18
+ afterEach(() => {
19
+ jest.clearAllMocks();
20
+ });
21
+
22
+ describe('Query.getAllUsers', () => {
23
+ it('should return all users', async () => {
24
+ const result = await userResolvers.Query.getAllUsers();
25
+ expect(result).toEqual([{ id: '1', name: 'John Doe', email: 'john@example.com' }]);
26
+ expect(mockGetUsers).toHaveBeenCalledTimes(1);
27
+ });
28
+ });
29
+
30
+ describe('Mutation.createUser', () => {
31
+ it('should create and return a new user', async () => {
32
+ const result = await userResolvers.Mutation.createUser(null, { name: 'Jane', email: 'jane@example.com' });
33
+ expect(result).toEqual({ id: '1', name: 'Jane', email: 'jane@example.com' });
34
+ expect(mockCreateUser).toHaveBeenCalledWith({ name: 'Jane', email: 'jane@example.com' });
35
+ expect(mockCreateUser).toHaveBeenCalledTimes(1);
36
+ });
37
+ });
38
+
39
+ describe('Mutation.updateUser', () => {
40
+ it('should update and return the user', async () => {
41
+ const payload = { name: 'Updated' };
42
+ const result = await userResolvers.Mutation.updateUser(null, { id: '1', ...payload });
43
+ expect(result).toMatchObject(payload);
44
+ });
45
+ });
46
+
47
+ describe('Mutation.deleteUser', () => {
48
+ it('should delete and return true', async () => {
49
+ const result = await userResolvers.Mutation.deleteUser(null, { id: '1' });
50
+ expect(result).toBe(true);
51
+ });
52
+ });
53
+ <%_ if (database === 'MongoDB') { -%>
54
+ describe('User.id', () => {
55
+ it('should return parent.id if available', () => {
56
+ const parent = { id: '123' };
57
+ const result = userResolvers.User.id(parent as { id?: string; _id?: unknown });
58
+ expect(result).toBe('123');
59
+ });
60
+
61
+ it('should fallback to parent._id if id is not available', () => {
62
+ const parent = { _id: '456' };
63
+ const result = userResolvers.User.id(parent as { id?: string; _id?: unknown });
64
+ expect(result).toBe('456');
65
+ });
66
+ });
67
+ <%_ } -%>
68
+ });
@@ -1,21 +1,29 @@
1
- import { UserController } from '@/interfaces/controllers/userController';
2
-
3
- const userController = new UserController();
4
-
5
- export const userResolvers = {
6
- Query: {
7
- getAllUsers: async () => {
8
- const users = await userController.getUsers();
9
- return users;
10
- }
11
- },
12
- Mutation: {
13
- createUser: async (_: unknown, { name, email }: { name: string, email: string }) => {
14
- const user = await userController.createUser({ name, email });
15
- return user;
16
- }
17
- }<%_ if (database === 'MongoDB') { -%>,
18
- User: {
19
- id: (parent: { id?: string; _id?: unknown }) => parent.id || parent._id
20
- }<%_ } %>
21
- };
1
+ import { UserController } from '@/interfaces/controllers/userController';
2
+
3
+ const userController = new UserController();
4
+
5
+ export const userResolvers = {
6
+ Query: {
7
+ getAllUsers: async () => {
8
+ const users = await userController.getUsers();
9
+ return users;
10
+ }
11
+ },
12
+ Mutation: {
13
+ createUser: async (_: unknown, { name, email }: { name: string, email: string }) => {
14
+ const user = await userController.createUser({ name, email });
15
+ return user;
16
+ },
17
+ updateUser: async (_: unknown, { id, name, email }: { id: string, name?: string, email?: string }) => {
18
+ const user = await userController.updateUser(id, { name, email });
19
+ return user;
20
+ },
21
+ deleteUser: async (_: unknown, { id }: { id: string }) => {
22
+ const result = await userController.deleteUser(id);
23
+ return result;
24
+ }
25
+ }<%_ if (database === 'MongoDB') { -%>,
26
+ User: {
27
+ id: (parent: { id?: string; _id?: unknown }) => parent.id || parent._id
28
+ }<%_ } %>
29
+ };
@@ -1,15 +1,17 @@
1
- export const userTypes = `#graphql
2
- type User {
3
- id: ID!
4
- name: String!
5
- email: String!
6
- }
7
-
8
- type Query {
9
- getAllUsers: [User]
10
- }
11
-
12
- type Mutation {
13
- createUser(name: String!, email: String!): User
14
- }
15
- `;
1
+ export const userTypes = `#graphql
2
+ type User {
3
+ id: ID!
4
+ name: String!
5
+ email: String!
6
+ }
7
+
8
+ type Query {
9
+ getAllUsers: [User]
10
+ }
11
+
12
+ type Mutation {
13
+ createUser(name: String!, email: String!): User
14
+ updateUser(id: ID!, name: String, email: String): User
15
+ deleteUser(id: ID!): Boolean
16
+ }
17
+ `;
@@ -1,11 +1,13 @@
1
- import { Router, Request, Response, NextFunction } from 'express';
2
- import { UserController } from '@/interfaces/controllers/userController';
3
-
4
- const router = Router();
5
- const userController = new UserController();
6
-
7
- router.post('/', (req: Request, res: Response, next: NextFunction) => userController.createUser(req, res, next));
8
- router.get('/', (req: Request, res: Response, next: NextFunction) => userController.getUsers(req, res, next));
9
-
10
- export default router;
11
-
1
+ import { Router, Request, Response, NextFunction } from 'express';
2
+ import { UserController } from '@/interfaces/controllers/userController';
3
+
4
+ const router = Router();
5
+ const userController = new UserController();
6
+
7
+ router.post('/', (req: Request, res: Response, next: NextFunction) => userController.createUser(req, res, next));
8
+ router.get('/', (req: Request, res: Response, next: NextFunction) => userController.getUsers(req, res, next));
9
+ router.patch('/:id', (req: Request, res: Response, next: NextFunction) => userController.updateUser(req, res, next));
10
+ router.delete('/:id', (req: Request, res: Response, next: NextFunction) => userController.deleteUser(req, res, next));
11
+
12
+ export default router;
13
+
@@ -0,0 +1,47 @@
1
+ import DeleteUser from '@/usecases/deleteUser';
2
+ import { UserRepository } from '@/infrastructure/repositories/UserRepository';
3
+ <%_ if (caching !== 'None') { -%>
4
+ import cacheService from '<% if (caching === "Redis") { %>@/infrastructure/caching/redisClient<% } else { %>@/infrastructure/caching/memoryCache<% } %>';
5
+ <%_ } -%>
6
+
7
+ jest.mock('@/infrastructure/repositories/UserRepository');
8
+ <%_ if (caching !== 'None') { -%>
9
+ jest.mock('<% if (caching === "Redis") { %>@/infrastructure/caching/redisClient<% } else { %>@/infrastructure/caching/memoryCache<% } %>', () => ({
10
+ get: jest.fn(),
11
+ set: jest.fn(),
12
+ del: jest.fn()
13
+ }));
14
+ <%_ } -%>
15
+
16
+ describe('DeleteUser UseCase', () => {
17
+ let deleteUser: DeleteUser;
18
+ let mockUserRepository: jest.Mocked<UserRepository>;
19
+
20
+ beforeEach(() => {
21
+ mockUserRepository = new UserRepository() as jest.Mocked<UserRepository>;
22
+ deleteUser = new DeleteUser(mockUserRepository);
23
+ jest.clearAllMocks();
24
+ });
25
+
26
+ it('should delete and return the user', async () => {
27
+ const id = 1;
28
+ const expectedResult = { id, name: 'Deleted User', email: 'test@test.com' };
29
+
30
+ mockUserRepository.delete.mockResolvedValue(expectedResult as any);
31
+
32
+ const result = await deleteUser.execute(id);
33
+
34
+ expect(mockUserRepository.delete).toHaveBeenCalledWith(id);
35
+ expect(result).toEqual(expectedResult);
36
+ <%_ if (caching !== 'None') { -%>
37
+ expect(cacheService.del).toHaveBeenCalledWith('users:all');
38
+ <%_ } %>
39
+ });
40
+
41
+ it('should throw an error if repository fails', async () => {
42
+ const error = new Error('Database error');
43
+ mockUserRepository.delete.mockRejectedValue(error);
44
+
45
+ await expect(deleteUser.execute(1)).rejects.toThrow(error);
46
+ });
47
+ });
@@ -0,0 +1,9 @@
1
+ import { UserRepository } from '@/infrastructure/repositories/UserRepository';
2
+
3
+ export default class DeleteUser {
4
+ constructor(private userRepository: UserRepository) {}
5
+
6
+ async execute(id: number | string) {
7
+ return this.userRepository.delete(id);
8
+ }
9
+ }
@@ -0,0 +1,48 @@
1
+ import UpdateUser from '@/usecases/updateUser';
2
+ import { UserRepository } from '@/infrastructure/repositories/UserRepository';
3
+ <%_ if (caching !== 'None') { -%>
4
+ import cacheService from '<% if (caching === "Redis") { %>@/infrastructure/caching/redisClient<% } else { %>@/infrastructure/caching/memoryCache<% } %>';
5
+ <%_ } -%>
6
+
7
+ jest.mock('@/infrastructure/repositories/UserRepository');
8
+ <%_ if (caching !== 'None') { -%>
9
+ jest.mock('<% if (caching === "Redis") { %>@/infrastructure/caching/redisClient<% } else { %>@/infrastructure/caching/memoryCache<% } %>', () => ({
10
+ get: jest.fn(),
11
+ set: jest.fn(),
12
+ del: jest.fn()
13
+ }));
14
+ <%_ } -%>
15
+
16
+ describe('UpdateUser UseCase', () => {
17
+ let updateUser: UpdateUser;
18
+ let mockUserRepository: jest.Mocked<UserRepository>;
19
+
20
+ beforeEach(() => {
21
+ mockUserRepository = new UserRepository() as jest.Mocked<UserRepository>;
22
+ updateUser = new UpdateUser(mockUserRepository);
23
+ jest.clearAllMocks();
24
+ });
25
+
26
+ it('should update and return the user', async () => {
27
+ const id = 1;
28
+ const data = { name: 'Updated Name' };
29
+ const expectedUser = { id, name: 'Updated Name', email: 'test@test.com' };
30
+
31
+ mockUserRepository.update.mockResolvedValue(expectedUser as any);
32
+
33
+ const result = await updateUser.execute(id, data);
34
+
35
+ expect(mockUserRepository.update).toHaveBeenCalledWith(id, data);
36
+ expect(result).toEqual(expectedUser);
37
+ <%_ if (caching !== 'None') { -%>
38
+ expect(cacheService.del).toHaveBeenCalledWith('users:all');
39
+ <%_ } %>
40
+ });
41
+
42
+ it('should throw an error if repository fails', async () => {
43
+ const error = new Error('Database error');
44
+ mockUserRepository.update.mockRejectedValue(error);
45
+
46
+ await expect(updateUser.execute(1, { name: 'Test' })).rejects.toThrow(error);
47
+ });
48
+ });
@@ -0,0 +1,9 @@
1
+ import { UserRepository } from '@/infrastructure/repositories/UserRepository';
2
+
3
+ export default class UpdateUser {
4
+ constructor(private userRepository: UserRepository) {}
5
+
6
+ async execute(id: number | string, data: { name?: string, email?: string }) {
7
+ return this.userRepository.update(id, data);
8
+ }
9
+ }
@@ -0,0 +1,12 @@
1
+ export const ERROR_MESSAGES = {
2
+ USER_NOT_FOUND: 'User not found',
3
+ RESOURCE_NOT_FOUND: 'Resource not found',
4
+ INVALID_USER_DATA: 'Invalid user event data',
5
+ INTERNAL_SERVER_ERROR: 'Internal Server Error',
6
+ BAD_REQUEST: 'Bad Request',
7
+ FETCH_USERS_ERROR: 'Error fetching users',
8
+ CREATE_USER_ERROR: 'Error creating user',
9
+ UPDATE_USER_ERROR: 'Error updating user',
10
+ DELETE_USER_ERROR: 'Error deleting user',
11
+ DATABASE_PING_FAILED: 'Health Check Database Ping Failed',
12
+ } as const;