nodejs-quickstart-structure 1.13.0 → 1.14.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.
- package/CHANGELOG.md +13 -0
- package/README.md +4 -3
- package/lib/generator.js +17 -3
- package/lib/modules/app-setup.js +111 -19
- package/lib/modules/caching-setup.js +13 -0
- package/lib/modules/config-files.js +25 -62
- package/lib/modules/database-setup.js +35 -30
- package/lib/modules/kafka-setup.js +78 -10
- package/package.json +1 -2
- package/templates/clean-architecture/js/src/errors/BadRequestError.js +1 -1
- package/templates/clean-architecture/js/src/errors/BadRequestError.spec.js.ejs +21 -0
- package/templates/clean-architecture/js/src/errors/NotFoundError.js +1 -1
- package/templates/clean-architecture/js/src/errors/NotFoundError.spec.js.ejs +21 -0
- package/templates/clean-architecture/js/src/infrastructure/log/logger.spec.js.ejs +63 -0
- package/templates/clean-architecture/js/src/infrastructure/repositories/UserRepository.js.ejs +2 -3
- package/templates/clean-architecture/js/src/infrastructure/repositories/UserRepository.spec.js.ejs +81 -0
- package/templates/clean-architecture/js/src/interfaces/controllers/userController.js.ejs +8 -4
- package/templates/clean-architecture/js/src/interfaces/controllers/userController.spec.js.ejs +102 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/context.spec.js.ejs +31 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/resolvers/user.resolvers.spec.js.ejs +49 -0
- package/templates/clean-architecture/js/src/interfaces/routes/api.spec.js.ejs +38 -0
- package/templates/clean-architecture/js/src/usecases/CreateUser.spec.js.ejs +51 -0
- package/templates/clean-architecture/js/src/usecases/GetAllUsers.spec.js.ejs +61 -0
- package/templates/clean-architecture/ts/src/errors/BadRequestError.spec.ts.ejs +21 -0
- package/templates/clean-architecture/ts/src/errors/BadRequestError.ts +1 -1
- package/templates/clean-architecture/ts/src/errors/NotFoundError.spec.ts.ejs +21 -0
- package/templates/clean-architecture/ts/src/errors/NotFoundError.ts +1 -1
- package/templates/clean-architecture/ts/src/infrastructure/log/logger.spec.ts.ejs +64 -0
- package/templates/clean-architecture/ts/src/infrastructure/repositories/UserRepository.spec.ts.ejs +85 -0
- package/templates/clean-architecture/ts/src/infrastructure/repositories/UserRepository.ts.ejs +2 -3
- package/templates/clean-architecture/ts/src/interfaces/controllers/userController.spec.ts.ejs +166 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/context.spec.ts.ejs +32 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/resolvers/user.resolvers.spec.ts.ejs +51 -0
- package/templates/clean-architecture/ts/src/interfaces/routes/userRoutes.spec.ts.ejs +40 -0
- package/templates/clean-architecture/ts/src/usecases/createUser.spec.ts.ejs +51 -0
- package/templates/clean-architecture/ts/src/usecases/getAllUsers.spec.ts.ejs +63 -0
- package/templates/clean-architecture/ts/src/utils/errorMiddleware.ts.ejs +1 -2
- package/templates/common/caching/js/memoryCache.spec.js.ejs +101 -0
- package/templates/common/caching/js/redisClient.spec.js.ejs +149 -0
- package/templates/common/caching/ts/memoryCache.spec.ts.ejs +102 -0
- package/templates/common/caching/ts/redisClient.spec.ts.ejs +157 -0
- package/templates/common/database/js/database.spec.js.ejs +56 -0
- package/templates/common/database/js/models/User.js.ejs +22 -0
- package/templates/common/database/js/models/User.spec.js.ejs +84 -0
- package/templates/common/database/js/mongoose.spec.js.ejs +43 -0
- package/templates/common/database/ts/database.spec.ts.ejs +56 -0
- package/templates/common/database/ts/models/User.spec.ts.ejs +84 -0
- package/templates/common/database/ts/models/User.ts.ejs +26 -0
- package/templates/common/database/ts/mongoose.spec.ts.ejs +42 -0
- package/templates/common/eslint.config.mjs.ejs +11 -2
- package/templates/common/health/js/healthRoute.spec.js.ejs +70 -0
- package/templates/common/health/ts/healthRoute.spec.ts.ejs +76 -0
- package/templates/common/jest.config.js.ejs +19 -5
- package/templates/common/kafka/js/config/kafka.spec.js.ejs +21 -0
- package/templates/common/kafka/js/services/kafkaService.js.ejs +9 -5
- package/templates/common/kafka/js/services/kafkaService.spec.js.ejs +60 -0
- package/templates/common/kafka/ts/config/kafka.spec.ts.ejs +21 -0
- package/templates/common/kafka/ts/services/kafkaService.spec.ts.ejs +61 -0
- package/templates/common/kafka/ts/services/kafkaService.ts.ejs +1 -1
- package/templates/common/package.json.ejs +0 -3
- package/templates/common/shutdown/js/gracefulShutdown.spec.js.ejs +160 -0
- package/templates/common/shutdown/ts/gracefulShutdown.spec.ts.ejs +158 -0
- package/templates/common/src/utils/errorMiddleware.spec.js.ejs +79 -0
- package/templates/common/src/utils/errorMiddleware.spec.ts.ejs +94 -0
- package/templates/common/tsconfig.json +1 -1
- package/templates/mvc/js/src/controllers/userController.js.ejs +4 -31
- package/templates/mvc/js/src/controllers/userController.spec.js.ejs +170 -0
- package/templates/mvc/js/src/errors/BadRequestError.js +1 -1
- package/templates/mvc/js/src/errors/BadRequestError.spec.js.ejs +21 -0
- package/templates/mvc/js/src/errors/NotFoundError.js +1 -1
- package/templates/mvc/js/src/errors/NotFoundError.spec.js.ejs +21 -0
- package/templates/mvc/js/src/graphql/context.spec.js.ejs +29 -0
- package/templates/mvc/js/src/graphql/resolvers/user.resolvers.spec.js.ejs +47 -0
- package/templates/mvc/js/src/index.js.ejs +1 -1
- package/templates/mvc/js/src/routes/api.spec.js.ejs +36 -0
- package/templates/mvc/js/src/utils/logger.spec.js.ejs +63 -0
- package/templates/mvc/ts/src/controllers/userController.spec.ts.ejs +185 -0
- package/templates/mvc/ts/src/controllers/userController.ts.ejs +4 -31
- package/templates/mvc/ts/src/errors/BadRequestError.spec.ts.ejs +21 -0
- package/templates/mvc/ts/src/errors/BadRequestError.ts +1 -1
- package/templates/mvc/ts/src/errors/NotFoundError.spec.ts.ejs +21 -0
- package/templates/mvc/ts/src/errors/NotFoundError.ts +1 -1
- package/templates/mvc/ts/src/graphql/context.spec.ts.ejs +30 -0
- package/templates/mvc/ts/src/graphql/resolvers/user.resolvers.spec.ts.ejs +51 -0
- package/templates/mvc/ts/src/routes/api.spec.ts.ejs +40 -0
- package/templates/mvc/ts/src/utils/errorMiddleware.ts.ejs +1 -2
- package/templates/mvc/ts/src/utils/logger.spec.ts.ejs +64 -0
- package/docs/demo.gif +0 -0
- package/docs/generateCase.md +0 -265
- package/docs/generatorFlow.md +0 -233
- package/docs/releaseNoteRule.md +0 -42
- package/docs/ruleDevelop.md +0 -30
- package/templates/common/tests/health.test.ts.ejs +0 -24
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import GetAllUsers from '@/usecases/getAllUsers';
|
|
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('GetAllUsers UseCase', () => {
|
|
17
|
+
let getAllUsers: GetAllUsers;
|
|
18
|
+
let mockUserRepository: jest.Mocked<UserRepository>;
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
mockUserRepository = new UserRepository() as jest.Mocked<UserRepository>;
|
|
22
|
+
getAllUsers = new GetAllUsers(mockUserRepository);
|
|
23
|
+
jest.clearAllMocks();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('should retrieve all users', async () => {
|
|
27
|
+
const expectedUsers = [{ id: 1, name: 'Alice', email: 'alice@example.com' }];
|
|
28
|
+
mockUserRepository.getUsers.mockResolvedValue(expectedUsers as any);
|
|
29
|
+
<%_ if (caching !== 'None') { -%>
|
|
30
|
+
(cacheService.get as jest.Mock).mockResolvedValue(null);
|
|
31
|
+
<%_ } %>
|
|
32
|
+
|
|
33
|
+
const result = await getAllUsers.execute();
|
|
34
|
+
|
|
35
|
+
expect(mockUserRepository.getUsers).toHaveBeenCalledTimes(1);
|
|
36
|
+
expect(result).toEqual(expectedUsers);
|
|
37
|
+
<%_ if (caching !== 'None') { -%>
|
|
38
|
+
expect(cacheService.set).toHaveBeenCalled();
|
|
39
|
+
<%_ } %>
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
<%_ if (caching !== 'None') { -%>
|
|
43
|
+
it('should return from cache if available', async () => {
|
|
44
|
+
const cachedUsers = [{ id: 1, name: 'Cached', email: 'cached@example.com' }];
|
|
45
|
+
(cacheService.get as jest.Mock).mockResolvedValue(cachedUsers);
|
|
46
|
+
|
|
47
|
+
const result = await getAllUsers.execute();
|
|
48
|
+
|
|
49
|
+
expect(mockUserRepository.getUsers).not.toHaveBeenCalled();
|
|
50
|
+
expect(result).toEqual(cachedUsers);
|
|
51
|
+
});
|
|
52
|
+
<%_ } -%>
|
|
53
|
+
|
|
54
|
+
it('should throw an error if repository fails', async () => {
|
|
55
|
+
const error = new Error('Database error');
|
|
56
|
+
mockUserRepository.getUsers.mockRejectedValue(error);
|
|
57
|
+
<%_ if (caching !== 'None') { -%>
|
|
58
|
+
(cacheService.get as jest.Mock).mockResolvedValue(null);
|
|
59
|
+
<%_ } -%>
|
|
60
|
+
|
|
61
|
+
await expect(getAllUsers.execute()).rejects.toThrow(error);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -3,8 +3,7 @@ import logger from '@/infrastructure/log/logger';
|
|
|
3
3
|
import { ApiError } from '@/errors/ApiError';
|
|
4
4
|
import { HTTP_STATUS } from '@/utils/httpCodes';
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
export const errorMiddleware = (err: Error, req: Request, res: Response, next: unknown) => {
|
|
6
|
+
export const errorMiddleware = (err: Error, req: Request, res: Response, _next: unknown) => {
|
|
8
7
|
let error = err;
|
|
9
8
|
|
|
10
9
|
if (!(error instanceof ApiError)) {
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
jest.mock('node-cache', () => {
|
|
2
|
+
return jest.fn().mockImplementation(() => ({
|
|
3
|
+
get: jest.fn(),
|
|
4
|
+
set: jest.fn(),
|
|
5
|
+
del: jest.fn(),
|
|
6
|
+
}));
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
jest.mock('<%- loggerPath %>', () => ({
|
|
10
|
+
info: jest.fn(),
|
|
11
|
+
error: jest.fn(),
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
describe('Memory Cache Client', () => {
|
|
15
|
+
let memoryCacheService;
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
jest.clearAllMocks();
|
|
19
|
+
jest.resetModules();
|
|
20
|
+
memoryCacheService = require('<% if (architecture === "MVC") { %>@/config/memoryCache<% } else { %>@/infrastructure/caching/memoryCache<% } %>');
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('should get data from memory cache', async () => {
|
|
24
|
+
const mockData = { test: 'data' };
|
|
25
|
+
memoryCacheService.cache.get.mockReturnValue(JSON.stringify(mockData));
|
|
26
|
+
|
|
27
|
+
const data = await memoryCacheService.get('test-key');
|
|
28
|
+
expect(data).toEqual(mockData);
|
|
29
|
+
expect(memoryCacheService.cache.get).toHaveBeenCalledWith('test-key');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('should return null when key is not found', async () => {
|
|
33
|
+
memoryCacheService.cache.get.mockReturnValue(undefined);
|
|
34
|
+
const data = await memoryCacheService.get('non-existent');
|
|
35
|
+
expect(data).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should return data as is if not a string', async () => {
|
|
39
|
+
const mockData = { test: 'data' };
|
|
40
|
+
memoryCacheService.cache.get.mockReturnValue(mockData);
|
|
41
|
+
const data = await memoryCacheService.get('binary-key');
|
|
42
|
+
expect(data).toEqual(mockData);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('should handle errors in get', async () => {
|
|
46
|
+
memoryCacheService.cache.get.mockImplementation(() => { throw new Error('Cache Error'); });
|
|
47
|
+
const data = await memoryCacheService.get('error-key');
|
|
48
|
+
expect(data).toBeNull();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('should set data to memory cache without TTL', async () => {
|
|
52
|
+
const mockData = { test: 'data' };
|
|
53
|
+
await memoryCacheService.set('test-key', mockData);
|
|
54
|
+
expect(memoryCacheService.cache.set).toHaveBeenCalledWith('test-key', JSON.stringify(mockData));
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should handle errors in set', async () => {
|
|
58
|
+
memoryCacheService.cache.set.mockImplementation(() => { throw new Error('Cache Error'); });
|
|
59
|
+
await memoryCacheService.set('test-key', 'value');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('should handle errors in del', async () => {
|
|
63
|
+
memoryCacheService.cache.del.mockImplementation(() => { throw new Error('Cache Error'); });
|
|
64
|
+
await memoryCacheService.del('test-key');
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should use getOrSet and call fetcher if not cached', async () => {
|
|
68
|
+
memoryCacheService.get = jest.fn().mockResolvedValue(null);
|
|
69
|
+
memoryCacheService.set = jest.fn();
|
|
70
|
+
const fetcher = jest.fn().mockResolvedValue({ new: 'data' });
|
|
71
|
+
|
|
72
|
+
const result = await memoryCacheService.getOrSet('new-key', fetcher);
|
|
73
|
+
|
|
74
|
+
expect(result).toEqual({ new: 'data' });
|
|
75
|
+
expect(fetcher).toHaveBeenCalled();
|
|
76
|
+
// Result should be cached
|
|
77
|
+
expect(memoryCacheService.set).toHaveBeenCalledWith('new-key', { new: 'data' }, 3600);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('should return cached data in getOrSet', async () => {
|
|
81
|
+
const cachedData = { cached: 'data' };
|
|
82
|
+
memoryCacheService.get = jest.fn().mockResolvedValue(cachedData);
|
|
83
|
+
const fetcher = jest.fn();
|
|
84
|
+
|
|
85
|
+
const result = await memoryCacheService.getOrSet('cached-key', fetcher);
|
|
86
|
+
|
|
87
|
+
expect(result).toEqual(cachedData);
|
|
88
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('should handle falsy data from fetcher in getOrSet', async () => {
|
|
92
|
+
memoryCacheService.get = jest.fn().mockResolvedValue(null);
|
|
93
|
+
memoryCacheService.set = jest.fn();
|
|
94
|
+
const fetcher = jest.fn().mockResolvedValue(null);
|
|
95
|
+
|
|
96
|
+
const result = await memoryCacheService.getOrSet('empty-key', fetcher);
|
|
97
|
+
|
|
98
|
+
expect(result).toBeNull();
|
|
99
|
+
expect(memoryCacheService.set).not.toHaveBeenCalled();
|
|
100
|
+
});
|
|
101
|
+
});
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const Redis = require('ioredis');
|
|
2
|
+
|
|
3
|
+
jest.mock('ioredis', () => {
|
|
4
|
+
const mRedis = jest.fn(() => ({
|
|
5
|
+
on: jest.fn(),
|
|
6
|
+
get: jest.fn(),
|
|
7
|
+
set: jest.fn(),
|
|
8
|
+
del: jest.fn(),
|
|
9
|
+
quit: jest.fn().mockResolvedValue('OK'),
|
|
10
|
+
}));
|
|
11
|
+
return mRedis;
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
jest.mock('dotenv', () => ({
|
|
15
|
+
config: jest.fn()
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
const mockLogger = {
|
|
19
|
+
info: jest.fn(),
|
|
20
|
+
error: jest.fn(),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
jest.mock('<%- loggerPath %>', () => mockLogger);
|
|
24
|
+
|
|
25
|
+
describe('Redis Service', () => {
|
|
26
|
+
let RedisService;
|
|
27
|
+
let logger;
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
jest.clearAllMocks();
|
|
31
|
+
jest.resetModules();
|
|
32
|
+
|
|
33
|
+
// Clean environment
|
|
34
|
+
const envVars = ['REDIS_HOST', 'REDIS_PORT', 'REDIS_PASSWORD'];
|
|
35
|
+
envVars.forEach(v => delete process.env[v]);
|
|
36
|
+
|
|
37
|
+
logger = require('<%- loggerPath %>');
|
|
38
|
+
RedisService = require('<%= redisClientPath %>');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('should handle redis events', () => {
|
|
42
|
+
// Find the event handlers
|
|
43
|
+
const handlers = {};
|
|
44
|
+
RedisService.client.on.mock.calls.forEach(([event, handler]) => {
|
|
45
|
+
handlers[event] = handler;
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
if (handlers['connect']) {
|
|
49
|
+
handlers['connect']();
|
|
50
|
+
expect(logger.info).toHaveBeenCalledWith('Redis connected');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (handlers['error']) {
|
|
54
|
+
handlers['error'](new Error('Test Error'));
|
|
55
|
+
expect(logger.error).toHaveBeenCalledWith('Redis error:', expect.any(Error));
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('should get data from redis', async () => {
|
|
60
|
+
const mockData = { test: 'data' };
|
|
61
|
+
RedisService.client.get.mockResolvedValue(JSON.stringify(mockData));
|
|
62
|
+
|
|
63
|
+
const data = await RedisService.get('test-key');
|
|
64
|
+
expect(data).toEqual(mockData);
|
|
65
|
+
expect(RedisService.client.get).toHaveBeenCalledWith('test-key');
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('should return null when key not found in redis', async () => {
|
|
69
|
+
RedisService.client.get.mockResolvedValue(null);
|
|
70
|
+
const data = await RedisService.get('non-existent');
|
|
71
|
+
expect(data).toBeNull();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('should handle errors in get', async () => {
|
|
75
|
+
RedisService.client.get.mockRejectedValue(new Error('Redis Error'));
|
|
76
|
+
const result = await RedisService.get('test-key');
|
|
77
|
+
expect(result).toBeNull();
|
|
78
|
+
expect(logger.error).toHaveBeenCalled();
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('should set data to redis without TTL', async () => {
|
|
82
|
+
const mockData = { test: 'data' };
|
|
83
|
+
await RedisService.set('test-key', mockData);
|
|
84
|
+
expect(RedisService.client.set).toHaveBeenCalledWith('test-key', JSON.stringify(mockData));
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('should set data to redis with TTL', async () => {
|
|
88
|
+
const mockData = { test: 'data' };
|
|
89
|
+
await RedisService.set('test-key', mockData, 3600);
|
|
90
|
+
expect(RedisService.client.set).toHaveBeenCalledWith('test-key', JSON.stringify(mockData), 'EX', 3600);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('should handle errors in set', async () => {
|
|
94
|
+
RedisService.client.set.mockRejectedValue(new Error('Redis Error'));
|
|
95
|
+
await RedisService.set('test-key', 'value');
|
|
96
|
+
expect(logger.error).toHaveBeenCalled();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it('should delete data from redis', async () => {
|
|
100
|
+
await RedisService.del('test-key');
|
|
101
|
+
expect(RedisService.client.del).toHaveBeenCalledWith('test-key');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('should handle errors in del', async () => {
|
|
105
|
+
RedisService.client.del.mockRejectedValue(new Error('Redis Error'));
|
|
106
|
+
await RedisService.del('test-key');
|
|
107
|
+
expect(logger.error).toHaveBeenCalled();
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('should use getOrSet and call fetcher if not cached', async () => {
|
|
111
|
+
RedisService.get = jest.fn().mockResolvedValue(null);
|
|
112
|
+
RedisService.set = jest.fn();
|
|
113
|
+
const fetcher = jest.fn().mockResolvedValue({ new: 'data' });
|
|
114
|
+
|
|
115
|
+
const result = await RedisService.getOrSet('new-key', fetcher);
|
|
116
|
+
|
|
117
|
+
expect(result).toEqual({ new: 'data' });
|
|
118
|
+
expect(fetcher).toHaveBeenCalled();
|
|
119
|
+
expect(RedisService.set).toHaveBeenCalledWith('new-key', { new: 'data' }, 3600);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('should use getOrSet and return cached data', async () => {
|
|
123
|
+
const cachedData = { cached: 'data' };
|
|
124
|
+
RedisService.get = jest.fn().mockResolvedValue(cachedData);
|
|
125
|
+
const fetcher = jest.fn();
|
|
126
|
+
|
|
127
|
+
const result = await RedisService.getOrSet('cached-key', fetcher);
|
|
128
|
+
|
|
129
|
+
expect(result).toEqual(cachedData);
|
|
130
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
it('should handle falsy data from fetcher in getOrSet', async () => {
|
|
134
|
+
RedisService.get = jest.fn().mockResolvedValue(null);
|
|
135
|
+
RedisService.set = jest.fn();
|
|
136
|
+
const fetcher = jest.fn().mockResolvedValue(null);
|
|
137
|
+
|
|
138
|
+
const result = await RedisService.getOrSet('empty-key', fetcher);
|
|
139
|
+
|
|
140
|
+
expect(result).toBeNull();
|
|
141
|
+
expect(RedisService.set).not.toHaveBeenCalled();
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('should quit the redis client', async () => {
|
|
145
|
+
const result = await RedisService.quit();
|
|
146
|
+
expect(result).toBe('OK');
|
|
147
|
+
expect(RedisService.client.quit).toHaveBeenCalled();
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
jest.mock('node-cache', () => {
|
|
2
|
+
return jest.fn().mockImplementation(() => ({
|
|
3
|
+
get: jest.fn(),
|
|
4
|
+
set: jest.fn(),
|
|
5
|
+
del: jest.fn(),
|
|
6
|
+
}));
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
jest.mock('<%- loggerPath %>', () => ({
|
|
10
|
+
info: jest.fn(),
|
|
11
|
+
error: jest.fn(),
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
describe('Memory Cache Client', () => {
|
|
15
|
+
let MemoryCacheService: any;
|
|
16
|
+
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
jest.clearAllMocks();
|
|
19
|
+
jest.resetModules();
|
|
20
|
+
MemoryCacheService = require('<% if (architecture === "MVC") { %>@/config/memoryCache<% } else { %>@/infrastructure/caching/memoryCache<% } %>').default;
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('should get data from memory cache', async () => {
|
|
24
|
+
const mockData = { test: 'data' };
|
|
25
|
+
MemoryCacheService.cache.get.mockReturnValue(JSON.stringify(mockData));
|
|
26
|
+
|
|
27
|
+
const data = await MemoryCacheService.get('test-key');
|
|
28
|
+
expect(data).toEqual(mockData);
|
|
29
|
+
expect(MemoryCacheService.cache.get).toHaveBeenCalledWith('test-key');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('should return null when key is not found', async () => {
|
|
33
|
+
MemoryCacheService.cache.get.mockReturnValue(undefined);
|
|
34
|
+
const data = await MemoryCacheService.get('non-existent');
|
|
35
|
+
expect(data).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('should return data as is if not a string', async () => {
|
|
39
|
+
const mockData = { test: 'data' };
|
|
40
|
+
MemoryCacheService.cache.get.mockReturnValue(mockData);
|
|
41
|
+
const data = await MemoryCacheService.get('binary-key');
|
|
42
|
+
expect(data).toEqual(mockData);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('should handle errors in get', async () => {
|
|
46
|
+
MemoryCacheService.cache.get.mockImplementation(() => { throw new Error('Cache Error'); });
|
|
47
|
+
const data = await MemoryCacheService.get('error-key');
|
|
48
|
+
expect(data).toBeNull();
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('should set data to memory cache without TTL', async () => {
|
|
52
|
+
const mockData = { test: 'data' };
|
|
53
|
+
await MemoryCacheService.set('test-key', mockData);
|
|
54
|
+
expect(MemoryCacheService.cache.set).toHaveBeenCalledWith('test-key', JSON.stringify(mockData));
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should handle errors in set', async () => {
|
|
58
|
+
MemoryCacheService.cache.set.mockImplementation(() => { throw new Error('Cache Error'); });
|
|
59
|
+
await MemoryCacheService.set('test-key', 'value');
|
|
60
|
+
// Should not throw
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('should handle errors in del', async () => {
|
|
64
|
+
MemoryCacheService.cache.del.mockImplementation(() => { throw new Error('Cache Error'); });
|
|
65
|
+
await MemoryCacheService.del('test-key');
|
|
66
|
+
// Should not throw
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('should use getOrSet and call fetcher if not cached', async () => {
|
|
70
|
+
MemoryCacheService.get = jest.fn().mockResolvedValue(null);
|
|
71
|
+
MemoryCacheService.set = jest.fn();
|
|
72
|
+
const fetcher = jest.fn().mockResolvedValue({ new: 'data' });
|
|
73
|
+
|
|
74
|
+
const result = await MemoryCacheService.getOrSet('new-key', fetcher);
|
|
75
|
+
|
|
76
|
+
expect(result).toEqual({ new: 'data' });
|
|
77
|
+
expect(fetcher).toHaveBeenCalled();
|
|
78
|
+
expect(MemoryCacheService.set).toHaveBeenCalledWith('new-key', { new: 'data' }, 3600);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('should return cached data in getOrSet', async () => {
|
|
82
|
+
const cachedData = { cached: 'data' };
|
|
83
|
+
MemoryCacheService.get = jest.fn().mockResolvedValue(cachedData);
|
|
84
|
+
const fetcher = jest.fn();
|
|
85
|
+
|
|
86
|
+
const result = await MemoryCacheService.getOrSet('cached-key', fetcher);
|
|
87
|
+
|
|
88
|
+
expect(result).toEqual(cachedData);
|
|
89
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('should handle falsy data from fetcher in getOrSet', async () => {
|
|
93
|
+
MemoryCacheService.get = jest.fn().mockResolvedValue(null);
|
|
94
|
+
MemoryCacheService.set = jest.fn();
|
|
95
|
+
const fetcher = jest.fn().mockResolvedValue(null);
|
|
96
|
+
|
|
97
|
+
const result = await MemoryCacheService.getOrSet('empty-key', fetcher);
|
|
98
|
+
|
|
99
|
+
expect(result).toBeNull();
|
|
100
|
+
expect(MemoryCacheService.set).not.toHaveBeenCalled();
|
|
101
|
+
});
|
|
102
|
+
});
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
jest.mock('ioredis', () => {
|
|
2
|
+
const mRedis = jest.fn(() => ({
|
|
3
|
+
on: jest.fn(),
|
|
4
|
+
get: jest.fn(),
|
|
5
|
+
set: jest.fn(),
|
|
6
|
+
del: jest.fn(),
|
|
7
|
+
quit: jest.fn().mockResolvedValue('OK'),
|
|
8
|
+
}));
|
|
9
|
+
return mRedis;
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
jest.mock('dotenv', () => ({
|
|
13
|
+
config: jest.fn()
|
|
14
|
+
}));
|
|
15
|
+
|
|
16
|
+
const mockLogger = {
|
|
17
|
+
info: jest.fn(),
|
|
18
|
+
error: jest.fn(),
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
jest.mock('<%- loggerPath %>', () => mockLogger);
|
|
22
|
+
|
|
23
|
+
describe('Redis Client', () => {
|
|
24
|
+
let RedisService: any;
|
|
25
|
+
let logger: any;
|
|
26
|
+
|
|
27
|
+
beforeEach(() => {
|
|
28
|
+
jest.clearAllMocks();
|
|
29
|
+
jest.resetModules();
|
|
30
|
+
|
|
31
|
+
// Clean environment
|
|
32
|
+
const envVars = ['REDIS_HOST', 'REDIS_PORT', 'REDIS_PASSWORD'];
|
|
33
|
+
envVars.forEach(v => delete process.env[v]);
|
|
34
|
+
|
|
35
|
+
logger = require('<%- loggerPath %>');
|
|
36
|
+
RedisService = require('<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>').default;
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('should initialize with default values when env vars are missing', () => {
|
|
40
|
+
delete process.env.REDIS_HOST;
|
|
41
|
+
delete process.env.REDIS_PORT;
|
|
42
|
+
delete process.env.REDIS_PASSWORD;
|
|
43
|
+
|
|
44
|
+
jest.resetModules();
|
|
45
|
+
const NewRedisService = require('<% if (architecture === "MVC") { %>@/config/redisClient<% } else { %>@/infrastructure/caching/redisClient<% } %>').default;
|
|
46
|
+
expect(NewRedisService).toBeDefined();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('should handle redis events', () => {
|
|
50
|
+
// Find the event handlers
|
|
51
|
+
const handlers: { [key: string]: (...args: any[]) => any } = {};
|
|
52
|
+
(RedisService.client.on as jest.Mock).mock.calls.forEach(([event, handler]) => {
|
|
53
|
+
handlers[event] = handler;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (handlers['connect']) {
|
|
57
|
+
handlers['connect']();
|
|
58
|
+
expect(logger.info).toHaveBeenCalledWith('Redis connected');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (handlers['error']) {
|
|
62
|
+
handlers['error'](new Error('Test Error'));
|
|
63
|
+
expect(logger.error).toHaveBeenCalledWith('Redis error:', expect.any(Error));
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should get data from redis', async () => {
|
|
68
|
+
const mockData = { test: 'data' };
|
|
69
|
+
RedisService.client.get.mockResolvedValue(JSON.stringify(mockData));
|
|
70
|
+
|
|
71
|
+
const data = await RedisService.get('test-key');
|
|
72
|
+
expect(data).toEqual(mockData);
|
|
73
|
+
expect(RedisService.client.get).toHaveBeenCalledWith('test-key');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('should return null when key not found in redis', async () => {
|
|
77
|
+
RedisService.client.get.mockResolvedValue(null);
|
|
78
|
+
const data = await RedisService.get('non-existent');
|
|
79
|
+
expect(data).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('should handle errors in get', async () => {
|
|
83
|
+
RedisService.client.get.mockRejectedValue(new Error('Redis Error'));
|
|
84
|
+
const result = await RedisService.get('test-key');
|
|
85
|
+
expect(result).toBeNull();
|
|
86
|
+
expect(logger.error).toHaveBeenCalled();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('should set data to redis without TTL', async () => {
|
|
90
|
+
const mockData = { test: 'data' };
|
|
91
|
+
await RedisService.set('test-key', mockData);
|
|
92
|
+
expect(RedisService.client.set).toHaveBeenCalledWith('test-key', JSON.stringify(mockData));
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('should set data to redis with TTL', async () => {
|
|
96
|
+
const mockData = { test: 'data' };
|
|
97
|
+
await RedisService.set('test-key', mockData, 3600);
|
|
98
|
+
expect(RedisService.client.set).toHaveBeenCalledWith('test-key', JSON.stringify(mockData), 'EX', 3600);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('should handle errors in set', async () => {
|
|
102
|
+
RedisService.client.set.mockRejectedValue(new Error('Redis Error'));
|
|
103
|
+
await RedisService.set('test-key', 'value');
|
|
104
|
+
expect(logger.error).toHaveBeenCalled();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('should delete data from redis', async () => {
|
|
108
|
+
await RedisService.del('test-key');
|
|
109
|
+
expect(RedisService.client.del).toHaveBeenCalledWith('test-key');
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('should handle errors in del', async () => {
|
|
113
|
+
RedisService.client.del.mockRejectedValue(new Error('Redis Error'));
|
|
114
|
+
await RedisService.del('test-key');
|
|
115
|
+
expect(logger.error).toHaveBeenCalled();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('should use getOrSet and call fetcher if not cached', async () => {
|
|
119
|
+
RedisService.get = jest.fn().mockResolvedValue(null);
|
|
120
|
+
RedisService.set = jest.fn();
|
|
121
|
+
const fetcher = jest.fn().mockResolvedValue({ new: 'data' });
|
|
122
|
+
|
|
123
|
+
const result = await RedisService.getOrSet('new-key', fetcher);
|
|
124
|
+
|
|
125
|
+
expect(result).toEqual({ new: 'data' });
|
|
126
|
+
expect(fetcher).toHaveBeenCalled();
|
|
127
|
+
expect(RedisService.set).toHaveBeenCalledWith('new-key', { new: 'data' }, 3600);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('should use getOrSet and return cached data', async () => {
|
|
131
|
+
const cachedData = { cached: 'data' };
|
|
132
|
+
RedisService.get = jest.fn().mockResolvedValue(cachedData);
|
|
133
|
+
const fetcher = jest.fn();
|
|
134
|
+
|
|
135
|
+
const result = await RedisService.getOrSet('cached-key', fetcher);
|
|
136
|
+
|
|
137
|
+
expect(result).toEqual(cachedData);
|
|
138
|
+
expect(fetcher).not.toHaveBeenCalled();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('should handle falsy data from fetcher in getOrSet', async () => {
|
|
142
|
+
RedisService.get = jest.fn().mockResolvedValue(null);
|
|
143
|
+
RedisService.set = jest.fn();
|
|
144
|
+
const fetcher = jest.fn().mockResolvedValue(null);
|
|
145
|
+
|
|
146
|
+
const result = await RedisService.getOrSet('empty-key', fetcher);
|
|
147
|
+
|
|
148
|
+
expect(result).toBeNull();
|
|
149
|
+
expect(RedisService.set).not.toHaveBeenCalled();
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('should quit the redis client', async () => {
|
|
153
|
+
const result = await RedisService.quit();
|
|
154
|
+
expect(result).toBe('OK');
|
|
155
|
+
expect(RedisService.client.quit).toHaveBeenCalled();
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
jest.mock('sequelize', () => {
|
|
2
|
+
const mSequelize = jest.fn(() => ({
|
|
3
|
+
authenticate: jest.fn().mockResolvedValue(true),
|
|
4
|
+
define: jest.fn(),
|
|
5
|
+
}));
|
|
6
|
+
return { Sequelize: mSequelize };
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
jest.mock('dotenv', () => ({
|
|
10
|
+
config: jest.fn()
|
|
11
|
+
}));
|
|
12
|
+
|
|
13
|
+
describe('Database Configuration', () => {
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
jest.clearAllMocks();
|
|
16
|
+
jest.resetModules();
|
|
17
|
+
|
|
18
|
+
// Clean environment
|
|
19
|
+
const envVars = ['DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT'];
|
|
20
|
+
envVars.forEach(v => delete process.env[v]);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('should initialize Sequelize with environment variables', () => {
|
|
24
|
+
const { Sequelize: SequelizeMock } = require('sequelize');
|
|
25
|
+
process.env.DB_NAME = 'testdb';
|
|
26
|
+
process.env.DB_USER = 'testuser';
|
|
27
|
+
process.env.DB_PASSWORD = 'testpassword';
|
|
28
|
+
process.env.DB_HOST = 'localhost';
|
|
29
|
+
process.env.DB_PORT = '5432';
|
|
30
|
+
|
|
31
|
+
require('<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>');
|
|
32
|
+
|
|
33
|
+
expect(SequelizeMock).toHaveBeenCalledWith(
|
|
34
|
+
'testdb',
|
|
35
|
+
'testuser',
|
|
36
|
+
'testpassword',
|
|
37
|
+
expect.objectContaining({
|
|
38
|
+
host: 'localhost',
|
|
39
|
+
port: 5432
|
|
40
|
+
})
|
|
41
|
+
);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('should initialize Sequelize with default values when env vars are missing', () => {
|
|
45
|
+
const { Sequelize: SequelizeMock } = require('sequelize');
|
|
46
|
+
delete process.env.DB_NAME;
|
|
47
|
+
delete process.env.DB_USER;
|
|
48
|
+
delete process.env.DB_PASSWORD;
|
|
49
|
+
delete process.env.DB_HOST;
|
|
50
|
+
delete process.env.DB_PORT;
|
|
51
|
+
|
|
52
|
+
require('<% if (architecture === "MVC") { %>@/config/database<% } else { %>@/infrastructure/database/database<% } %>');
|
|
53
|
+
|
|
54
|
+
expect(SequelizeMock).toHaveBeenCalledTimes(1);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -1,3 +1,24 @@
|
|
|
1
|
+
<% if (database === 'None') { -%>
|
|
2
|
+
class UserModel {
|
|
3
|
+
static mockData = [];
|
|
4
|
+
|
|
5
|
+
static async find() {
|
|
6
|
+
return this.mockData;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
static async findAll() {
|
|
10
|
+
return this.mockData;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
static async create(data) {
|
|
14
|
+
const newUser = { id: String(this.mockData.length + 1), ...data };
|
|
15
|
+
this.mockData.push(newUser);
|
|
16
|
+
return newUser;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
module.exports = UserModel;
|
|
21
|
+
<% } else { -%>
|
|
1
22
|
const { DataTypes, Model } = require('sequelize');
|
|
2
23
|
<% if (architecture === 'MVC') { %>const sequelize = require('../config/database');<% } else { %>const sequelize = require('../database');<% } %>
|
|
3
24
|
|
|
@@ -28,3 +49,4 @@ User.init(
|
|
|
28
49
|
);
|
|
29
50
|
|
|
30
51
|
module.exports = User;
|
|
52
|
+
<% } -%>
|