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,158 +1,179 @@
1
- import { setupGracefulShutdown } from '@/utils/gracefulShutdown';
2
- import { Server } from 'http';
3
- <%_ if (database === 'MongoDB') { -%>
4
- import mongoose from 'mongoose';
5
- <%_ } else if (database !== 'None') { -%>
6
- import sequelize from '<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>';
7
- <%_ } -%>
8
- <%_ if (caching === 'Redis') { -%>
9
- import redisService from '<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>';
10
- <%_ } -%>
11
-
12
- <%_ if (database === 'MongoDB') { -%>
13
- jest.mock('mongoose', () => {
14
- return {
15
- __esModule: true,
16
- default: {
17
- connection: {
18
- close: jest.fn().mockResolvedValue(true)
19
- }
20
- }
21
- };
22
- });
23
- <%_ } else if (database !== 'None') { -%>
24
- jest.mock('<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>', () => {
25
- return {
26
- __esModule: true,
27
- default: {
28
- close: jest.fn().mockResolvedValue(true)
29
- }
30
- };
31
- });
32
- <%_ } -%>
33
-
34
- <%_ if (caching === 'Redis') { -%>
35
- jest.mock('<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>', () => {
36
- return {
37
- __esModule: true,
38
- default: {
39
- quit: jest.fn().mockResolvedValue(true)
40
- }
41
- };
42
- });
43
- <%_ } -%>
44
-
45
- const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
46
-
47
- describe('Graceful Shutdown', () => {
48
- let mockServer: Partial<Server>;
49
- let mockExit: jest.SpyInstance;
50
- let processListeners: Record<string, (...args: any[]) => void>;
51
- <%_ if (communication === 'Kafka') { -%>
52
- let mockKafkaService: { disconnect: jest.Mock };
53
- <%_ } -%>
54
-
55
- beforeEach(() => {
56
- jest.useFakeTimers({ legacyFakeTimers: true });
57
- jest.clearAllMocks();
58
- processListeners = {};
59
-
60
- mockServer = {
61
- close: jest.fn().mockImplementation((cb?: (err?: Error) => void) => {
62
- if (cb) Promise.resolve().then(() => cb());
63
- return mockServer;
64
- })
65
- };
66
-
67
- mockExit = jest.spyOn(process, 'exit').mockImplementation((() => {}) as any);
68
- jest.spyOn(process, 'on').mockImplementation(((event: string, handler: (...args: any[]) => void) => {
69
- processListeners[event] = handler;
70
- return process;
71
- }) as any);
72
-
73
- <%_ if (communication === 'Kafka') { -%>
74
- mockKafkaService = { disconnect: jest.fn().mockResolvedValue(true) };
75
- <%_ } -%>
76
- });
77
-
78
- afterEach(() => {
79
- jest.restoreAllMocks();
80
- jest.useRealTimers();
81
- });
82
-
83
- it('should register SIGTERM and SIGINT events', () => {
84
- setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
85
- expect(processListeners['SIGTERM']).toBeDefined();
86
- expect(processListeners['SIGINT']).toBeDefined();
87
- });
88
-
89
- it('should cleanly shutdown all connections and exit 0 on SIGTERM', async () => {
90
- setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
91
-
92
- processListeners['SIGTERM']();
93
-
94
- // Flush microtask queue multiple times for nested async operations
95
- await flushPromises();
96
- await flushPromises();
97
- await flushPromises();
98
-
99
- expect(mockServer.close).toHaveBeenCalled();
100
-
101
- <%_ if (database === 'MongoDB') { -%>
102
- expect(mongoose.connection.close).toHaveBeenCalledWith(false);
103
- <%_ } else if (database !== 'None') { -%>
104
- expect(sequelize.close).toHaveBeenCalled();
105
- <%_ } -%>
106
-
107
- <%_ if (caching === 'Redis') { -%>
108
- expect(redisService.quit).toHaveBeenCalled();
109
- <%_ } -%>
110
-
111
- <%_ if (communication === 'Kafka') { -%>
112
- expect(mockKafkaService.disconnect).toHaveBeenCalled();
113
- <%_ } -%>
114
-
115
- expect(mockExit).toHaveBeenCalledWith(0);
116
- });
117
-
118
- it('should exit 0 on SIGINT', async () => {
119
- setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
120
- processListeners['SIGINT']();
121
- await flushPromises();
122
- await flushPromises();
123
- expect(mockExit).toHaveBeenCalledWith(0);
124
- });
125
-
126
- <%_ if (communication === 'Kafka' || database !== 'None' || caching === 'Redis') { _%>
127
- it('should handle errors during shutdown and exit 1', async () => {
128
- <%_ if (communication === 'Kafka') { _%>
129
- mockKafkaService.disconnect.mockRejectedValueOnce(new Error('Shutdown Error'));
130
- <%_ } else if (database === 'MongoDB') { _%>
131
- (mongoose.connection.close as jest.Mock).mockRejectedValueOnce(new Error('Shutdown Error'));
132
- <%_ } else if (database !== 'None') { _%>
133
- (sequelize.close as jest.Mock).mockRejectedValueOnce(new Error('Shutdown Error'));
134
- <%_ } else if (caching === 'Redis') { _%>
135
- (redisService.quit as jest.Mock).mockRejectedValueOnce(new Error('Shutdown Error'));
136
- <%_ } _%>
137
-
138
- setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
139
- processListeners['SIGTERM']();
140
-
141
- await flushPromises();
142
- await flushPromises();
143
- await flushPromises();
144
-
145
- expect(mockExit).toHaveBeenCalledWith(1);
146
- });
147
-
148
- it('should forcefully shutdown if cleanup takes too long', async () => {
149
- setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
150
- processListeners['SIGTERM']();
151
-
152
- jest.advanceTimersByTime(15000);
153
-
154
- expect(mockExit).toHaveBeenCalledWith(1);
155
- });
156
- <%_ } _%>
157
-
158
- });
1
+ import { setupGracefulShutdown } from '@/utils/gracefulShutdown';
2
+ import { Server } from 'http';
3
+ <%_ if (database === 'MongoDB') { -%>
4
+ import mongoose from 'mongoose';
5
+ <%_ } else if (database !== 'None') { -%>
6
+ import sequelize from '<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>';
7
+ <%_ } -%>
8
+ <%_ if (caching === 'Redis') { -%>
9
+ import redisService from '<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>';
10
+ <%_ } -%>
11
+
12
+ <%_ if (database === 'MongoDB') { -%>
13
+ jest.mock('mongoose', () => {
14
+ return {
15
+ __esModule: true,
16
+ default: {
17
+ connection: {
18
+ close: jest.fn().mockResolvedValue(true)
19
+ }
20
+ }
21
+ };
22
+ });
23
+ <%_ } else if (database !== 'None') { -%>
24
+ jest.mock('<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>', () => {
25
+ return {
26
+ __esModule: true,
27
+ default: {
28
+ close: jest.fn().mockResolvedValue(true)
29
+ }
30
+ };
31
+ });
32
+ <%_ } -%>
33
+
34
+ <%_ if (caching === 'Redis') { -%>
35
+ jest.mock('<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>', () => {
36
+ return {
37
+ __esModule: true,
38
+ default: {
39
+ quit: jest.fn().mockResolvedValue(true)
40
+ }
41
+ };
42
+ });
43
+ <%_ } -%>
44
+
45
+ const flushPromises = () => new Promise((resolve) => setImmediate(resolve));
46
+
47
+ describe('Graceful Shutdown', () => {
48
+ let mockServer: Partial<Server>;
49
+ let mockExit: jest.SpyInstance;
50
+ let processListeners: Record<string, (...args: any[]) => void>;
51
+ <%_ if (communication === 'Kafka') { -%>
52
+ let mockKafkaService: { disconnect: jest.Mock };
53
+ <%_ } -%>
54
+
55
+ beforeEach(() => {
56
+ jest.useFakeTimers({ legacyFakeTimers: true });
57
+ jest.clearAllMocks();
58
+ processListeners = {};
59
+
60
+ mockServer = {
61
+ close: jest.fn().mockImplementation((cb?: (err?: Error) => void) => {
62
+ if (cb) Promise.resolve().then(() => cb());
63
+ return mockServer;
64
+ })
65
+ };
66
+
67
+ mockExit = jest.spyOn(process, 'exit').mockImplementation((() => {}) as any);
68
+ jest.spyOn(process, 'on').mockImplementation(((event: string, handler: (...args: any[]) => void) => {
69
+ processListeners[event] = handler;
70
+ return process;
71
+ }) as any);
72
+
73
+ <%_ if (communication === 'Kafka') { -%>
74
+ mockKafkaService = { disconnect: jest.fn().mockResolvedValue(true) };
75
+ <%_ } -%>
76
+ });
77
+
78
+ afterEach(() => {
79
+ jest.restoreAllMocks();
80
+ jest.useRealTimers();
81
+ });
82
+
83
+ it('should register SIGTERM and SIGINT events', () => {
84
+ setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
85
+ expect(processListeners['SIGTERM']).toBeDefined();
86
+ expect(processListeners['SIGINT']).toBeDefined();
87
+ });
88
+
89
+ it('should cleanly shutdown all connections and exit 0 on SIGTERM', async () => {
90
+ setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
91
+
92
+ processListeners['SIGTERM']();
93
+
94
+ // Flush microtask queue multiple times for nested async operations
95
+ await flushPromises();
96
+ await flushPromises();
97
+ await flushPromises();
98
+
99
+ expect(mockServer.close).toHaveBeenCalled();
100
+
101
+ <%_ if (database === 'MongoDB') { -%>
102
+ expect(mongoose.connection.close).toHaveBeenCalledWith(false);
103
+ <%_ } else if (database !== 'None') { -%>
104
+ expect(sequelize.close).toHaveBeenCalled();
105
+ <%_ } -%>
106
+
107
+ <%_ if (caching === 'Redis') { -%>
108
+ expect(redisService.quit).toHaveBeenCalled();
109
+ <%_ } -%>
110
+
111
+ <%_ if (communication === 'Kafka') { -%>
112
+ expect(mockKafkaService.disconnect).toHaveBeenCalled();
113
+ <%_ } -%>
114
+
115
+ expect(mockExit).toHaveBeenCalledWith(0);
116
+ });
117
+
118
+ it('should exit 0 on SIGINT', async () => {
119
+ setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
120
+ processListeners['SIGINT']();
121
+ await flushPromises();
122
+ await flushPromises();
123
+ expect(mockExit).toHaveBeenCalledWith(0);
124
+ });
125
+
126
+ <%_ if (communication === 'Kafka' || database !== 'None' || caching === 'Redis') { -%>
127
+ it('should handle errors during shutdown and exit 1', async () => {
128
+ <%_ if (communication === 'Kafka') { -%>
129
+ mockKafkaService.disconnect.mockRejectedValueOnce(new Error('Shutdown Error'));
130
+ <%_ if (database === 'MongoDB') { -%>
131
+ (mongoose.connection.close as jest.Mock).mockResolvedValueOnce(true);
132
+ <%_ } else if (database !== 'None') { -%>
133
+ (sequelize.close as jest.Mock).mockResolvedValueOnce(true);
134
+ <%_ } -%>
135
+ <%_ } else if (database === 'MongoDB') { -%>
136
+ (mongoose.connection.close as jest.Mock).mockRejectedValueOnce(new Error('Shutdown Error'));
137
+ <%_ } else if (database !== 'None') { -%>
138
+ (sequelize.close as jest.Mock).mockRejectedValueOnce(new Error('Shutdown Error'));
139
+ <%_ } else if (caching === 'Redis') { -%>
140
+ (redisService.quit as jest.Mock).mockRejectedValueOnce(new Error('Shutdown Error'));
141
+ <%_ } -%>
142
+
143
+ setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
144
+ processListeners['SIGTERM']();
145
+
146
+ await flushPromises();
147
+ await flushPromises();
148
+ await flushPromises();
149
+
150
+ expect(mockExit).toHaveBeenCalledWith(1);
151
+ });
152
+
153
+ it('should handle server close errors', async () => {
154
+ const serverError = new Error('Server Close Error');
155
+ mockServer.close = jest.fn().mockImplementation((cb?: (err?: Error) => void) => {
156
+ if (cb) Promise.resolve().then(() => cb(serverError));
157
+ return mockServer;
158
+ });
159
+
160
+ setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
161
+ processListeners['SIGTERM']();
162
+
163
+ await flushPromises();
164
+ // Since it's inside server.close callback, we need to wait
165
+ await flushPromises();
166
+
167
+ expect(mockExit).toHaveBeenCalledWith(1);
168
+ });
169
+
170
+ it('should forcefully shutdown if cleanup takes too long', async () => {
171
+ setupGracefulShutdown(mockServer as Server<% if (communication === 'Kafka') { %>, mockKafkaService<% } %>);
172
+ processListeners['SIGTERM']();
173
+
174
+ jest.advanceTimersByTime(15000);
175
+
176
+ expect(mockExit).toHaveBeenCalledWith(1);
177
+ });
178
+ <%_ } -%>
179
+ });
@@ -1,55 +1,59 @@
1
- import { Server } from 'http';
2
- <%_ if (architecture === 'MVC') { -%>
3
- import logger from '@/utils/logger';
4
- <%_ } else { -%>
5
- import logger from '@/infrastructure/log/logger';
6
- <%_ } -%>
7
- <%_ if (database === 'MongoDB') { -%>
8
- import mongoose from 'mongoose';
9
- <%_ } else if (database !== 'None') { -%>
10
- import sequelize from '<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>';
11
- <%_ } -%>
12
- <%_ if (caching === 'Redis') { -%>
13
- import redisService from '<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>';
14
- <%_ } -%>
15
-
16
- export const setupGracefulShutdown = (server: Server<% if (communication === 'Kafka') { %>, kafkaService: { disconnect: () => Promise<void> }<% } %>) => {
17
- const gracefulShutdown = async (signal: string) => {
18
- logger.info(`Received ${signal}. Shutting down gracefully...`);
19
- server.close(async () => {
20
- logger.info('HTTP server closed.');
21
- try {
22
- <%_ if (database !== 'None') { -%>
23
- <%_ if (database === 'MongoDB') { -%>
24
- await mongoose.connection.close(false);
25
- logger.info('MongoDB connection closed.');
26
- <%_ } else { -%>
27
- await sequelize.close();
28
- logger.info('Database connection closed.');
29
- <%_ } -%>
30
- <%_ } -%>
31
- <%_ if (caching === 'Redis') { -%>
32
- await redisService.quit();
33
- logger.info('Redis connection closed.');
34
- <%_ } -%>
35
- <%_ if (communication === 'Kafka') { -%>
36
- await kafkaService.disconnect();
37
- logger.info('Kafka connection closed.');
38
- <%_ } -%>
39
- logger.info('Graceful shutdown fully completed.');
40
- process.exit(0);
41
- } catch (err) {
42
- logger.error('Error during shutdown:', err);
43
- process.exit(1);
44
- }
45
- });
46
-
47
- setTimeout(() => {
48
- logger.error('Could not close connections in time, forcefully shutting down');
49
- process.exit(1);
50
- }, 15000);
51
- };
52
-
53
- process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
54
- process.on('SIGINT', () => gracefulShutdown('SIGINT'));
55
- };
1
+ import { Server } from 'http';
2
+ <%_ if (architecture === 'MVC') { -%>
3
+ import logger from '@/utils/logger';
4
+ <%_ } else { -%>
5
+ import logger from '@/infrastructure/log/logger';
6
+ <%_ } -%>
7
+ <%_ if (database === 'MongoDB') { -%>
8
+ import mongoose from 'mongoose';
9
+ <%_ } else if (database !== 'None') { -%>
10
+ import sequelize from '<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>';
11
+ <%_ } -%>
12
+ <%_ if (caching === 'Redis') { -%>
13
+ import redisService from '<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>';
14
+ <%_ } -%>
15
+
16
+ export const setupGracefulShutdown = (server: Server<% if (communication === 'Kafka') { %>, kafkaService: { disconnect: () => Promise<void> }<% } %>) => {
17
+ const gracefulShutdown = async (signal: string) => {
18
+ logger.info(`Received ${signal}. Shutting down gracefully...`);
19
+ server.close(async (err: Error | undefined) => {
20
+ if (err) {
21
+ logger.error('Error closing HTTP server:', err);
22
+ process.exit(1);
23
+ }
24
+ logger.info('HTTP server closed.');
25
+ try {
26
+ <%_ if (database !== 'None') { -%>
27
+ <%_ if (database === 'MongoDB') { -%>
28
+ await mongoose.connection.close(false);
29
+ logger.info('MongoDB connection closed.');
30
+ <%_ } else { -%>
31
+ await sequelize.close();
32
+ logger.info('Database connection closed.');
33
+ <%_ } -%>
34
+ <%_ } -%>
35
+ <%_ if (caching === 'Redis') { -%>
36
+ await redisService.quit();
37
+ logger.info('Redis connection closed.');
38
+ <%_ } -%>
39
+ <%_ if (communication === 'Kafka') { -%>
40
+ await kafkaService.disconnect();
41
+ logger.info('Kafka connection closed.');
42
+ <%_ } -%>
43
+ logger.info('Graceful shutdown fully completed.');
44
+ process.exit(0);
45
+ } catch (err) {
46
+ logger.error('Error during shutdown:', err);
47
+ process.exit(1);
48
+ }
49
+ });
50
+
51
+ setTimeout(() => {
52
+ logger.error('Could not close connections in time, forcefully shutting down');
53
+ process.exit(1);
54
+ }, 15000);
55
+ };
56
+
57
+ process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
58
+ process.on('SIGINT', () => gracefulShutdown('SIGINT'));
59
+ };
@@ -1,49 +1,120 @@
1
- const request = require('supertest');
2
-
3
- const SERVER_URL = process.env.TEST_URL || `http://127.0.0.1:${process.env.PORT || 3001}`;
4
-
5
- describe('E2E User Tests', () => {
6
- // Global setup and teardown hooks can be added here
7
- // typically for database seeding or external authentication checks prior to E2E.
8
- const uniqueEmail = `test_${Date.now()}@example.com`;
9
-
10
- <%_ if (communication === 'GraphQL') { _%>
11
- it('should create a user and verify flow via GraphQL', async () => {
12
- const query = `
13
- mutation {
14
- createUser(name: "Test User", email: "${uniqueEmail}") {
15
- id
16
- name
17
- email
18
- }
19
- }
20
- `;
21
- const response = await request(SERVER_URL)
22
- .post('/graphql')
23
- .send({ query });
24
-
25
- expect(response.statusCode).toBe(200);
26
- });
27
- <%_ } else if (communication === 'Kafka') { _%>
28
- it('should trigger Kafka event for user creation', async () => {
29
- const response = await request(SERVER_URL)
30
- .post('/api/users')
31
- .send({ name: 'Test User', email: uniqueEmail });
32
-
33
- // Assuming the API returns 201 or 404 (if no REST endpoint is exposed in Kafka skeleton)
34
- expect([201, 202, 404]).toContain(response.statusCode);
35
-
36
- // Wait for Kafka to process...
37
- await new Promise(resolve => setTimeout(resolve, 1000));
38
- });
39
- <%_ } else { _%>
40
- it('should create a user successfully via REST', async () => {
41
- const response = await request(SERVER_URL)
42
- .post('/api/users')
43
- .send({ name: 'Test User', email: uniqueEmail });
44
-
45
- // E2E Tests must have strict and deterministic assertions
46
- expect(response.statusCode).toBe(201);
47
- });
48
- <%_ } _%>
49
- });
1
+ const request = require('supertest');
2
+
3
+ const SERVER_URL = process.env.TEST_URL || `http://127.0.0.1:${process.env.PORT || 3001}`;
4
+
5
+ describe('E2E User Tests', () => {
6
+ // Global setup and teardown hooks can be added here
7
+ // typically for database seeding or external authentication checks prior to E2E.
8
+ let userId;
9
+ const uniqueEmail = `test_${Date.now()}@example.com`;
10
+
11
+ <%_ if (communication === 'GraphQL') { -%>
12
+ it('should create a user via GraphQL', async () => {
13
+ const query = `
14
+ mutation {
15
+ createUser(name: "Test User", email: "${uniqueEmail}") {
16
+ id
17
+ name
18
+ email
19
+ }
20
+ }
21
+ `;
22
+ const response = await request(SERVER_URL)
23
+ .post('/graphql')
24
+ .send({ query });
25
+
26
+ expect(response.statusCode).toBe(200);
27
+ userId = response.body.data.createUser.id;
28
+ expect(userId).toBeDefined();
29
+ });
30
+
31
+ it('should update a user via GraphQL', async () => {
32
+ const query = `
33
+ mutation {
34
+ updateUser(id: "${userId}", name: "Updated User") {
35
+ id
36
+ name
37
+ }
38
+ }
39
+ `;
40
+ const response = await request(SERVER_URL)
41
+ .post('/graphql')
42
+ .send({ query });
43
+
44
+ expect(response.statusCode).toBe(200);
45
+ expect(response.body.data.updateUser.name).toBe("Updated User");
46
+ });
47
+
48
+ it('should delete a user via GraphQL', async () => {
49
+ const query = `
50
+ mutation {
51
+ deleteUser(id: "${userId}")
52
+ }
53
+ `;
54
+ const response = await request(SERVER_URL)
55
+ .post('/graphql')
56
+ .send({ query });
57
+
58
+ expect(response.statusCode).toBe(200);
59
+ expect(response.body.data.deleteUser).toBe(true);
60
+ });
61
+ <%_ } else if (communication === 'Kafka') { -%>
62
+ it('should trigger Kafka event for user creation', async () => {
63
+ const response = await request(SERVER_URL)
64
+ .post('/api/users')
65
+ .send({ name: 'Test User', email: uniqueEmail });
66
+
67
+ expect([201, 202]).toContain(response.statusCode);
68
+ userId = response.body.id || response.body._id;
69
+ expect(userId).toBeDefined();
70
+
71
+ // Wait for Kafka to process...
72
+ await new Promise(resolve => setTimeout(resolve, 500));
73
+ });
74
+
75
+ it('should trigger Kafka event for user update', async () => {
76
+ const response = await request(SERVER_URL)
77
+ .patch(`/api/users/${userId}`)
78
+ .send({ name: 'Updated User' });
79
+
80
+ expect([200, 202, 204]).toContain(response.statusCode);
81
+
82
+ // Wait for Kafka to process...
83
+ await new Promise(resolve => setTimeout(resolve, 500));
84
+ });
85
+
86
+ it('should trigger Kafka event for user deletion', async () => {
87
+ const response = await request(SERVER_URL)
88
+ .delete(`/api/users/${userId}`);
89
+
90
+ expect([200, 202, 204]).toContain(response.statusCode);
91
+
92
+ // Wait for Kafka to process...
93
+ await new Promise(resolve => setTimeout(resolve, 500));
94
+ });
95
+ <%_ } else { -%>
96
+ it('should create a user successfully via REST', async () => {
97
+ const response = await request(SERVER_URL)
98
+ .post('/api/users')
99
+ .send({ name: 'Test User', email: uniqueEmail });
100
+
101
+ expect(response.statusCode).toBe(201);
102
+ userId = response.body.id || response.body._id;
103
+ });
104
+
105
+ it('should update a user successfully via REST', async () => {
106
+ const response = await request(SERVER_URL)
107
+ .patch(`/api/users/${userId}`)
108
+ .send({ name: 'Updated User' });
109
+
110
+ expect(response.statusCode).toBe(200);
111
+ });
112
+
113
+ it('should delete a user successfully via REST', async () => {
114
+ const response = await request(SERVER_URL)
115
+ .delete(`/api/users/${userId}`);
116
+
117
+ expect(response.statusCode).toBe(200);
118
+ });
119
+ <%_ } -%>
120
+ });