nodejs-structure-cli 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/bin/index.js +143 -0
- package/lib/generator.js +145 -0
- package/lib/modules/app-setup.js +479 -0
- package/lib/modules/caching-setup.js +76 -0
- package/lib/modules/config-files.js +151 -0
- package/lib/modules/database-setup.js +116 -0
- package/lib/modules/kafka-setup.js +249 -0
- package/lib/modules/project-setup.js +32 -0
- package/lib/prompts.js +128 -0
- package/package.json +66 -0
- package/templates/clean-architecture/js/src/domain/models/User.js.ejs +11 -0
- package/templates/clean-architecture/js/src/errors/ApiError.js +14 -0
- package/templates/clean-architecture/js/src/errors/BadRequestError.js +11 -0
- package/templates/clean-architecture/js/src/errors/BadRequestError.spec.js.ejs +22 -0
- package/templates/clean-architecture/js/src/errors/NotFoundError.js +11 -0
- package/templates/clean-architecture/js/src/errors/NotFoundError.spec.js.ejs +22 -0
- package/templates/clean-architecture/js/src/index.js.ejs +56 -0
- package/templates/clean-architecture/js/src/infrastructure/config/env.js.ejs +47 -0
- package/templates/clean-architecture/js/src/infrastructure/log/logger.js +36 -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 +88 -0
- package/templates/clean-architecture/js/src/infrastructure/repositories/UserRepository.spec.js.ejs +142 -0
- package/templates/clean-architecture/js/src/infrastructure/webserver/middleware/errorMiddleware.js +30 -0
- package/templates/clean-architecture/js/src/infrastructure/webserver/server.js.ejs +93 -0
- package/templates/clean-architecture/js/src/infrastructure/webserver/swagger.js.ejs +6 -0
- package/templates/clean-architecture/js/src/interfaces/controllers/userController.js.ejs +190 -0
- package/templates/clean-architecture/js/src/interfaces/controllers/userController.spec.js.ejs +234 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/context.js.ejs +13 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/context.spec.js.ejs +31 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/index.js.ejs +5 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/resolvers/index.js.ejs +6 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/resolvers/user.resolvers.js.ejs +27 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/resolvers/user.resolvers.spec.js.ejs +66 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/typeDefs/index.js.ejs +6 -0
- package/templates/clean-architecture/js/src/interfaces/graphql/typeDefs/user.types.js.ejs +19 -0
- package/templates/clean-architecture/js/src/interfaces/routes/api.js.ejs +17 -0
- package/templates/clean-architecture/js/src/interfaces/routes/api.spec.js.ejs +38 -0
- package/templates/clean-architecture/js/src/usecases/CreateUser.js.ejs +14 -0
- package/templates/clean-architecture/js/src/usecases/CreateUser.spec.js.ejs +51 -0
- package/templates/clean-architecture/js/src/usecases/DeleteUser.js +11 -0
- package/templates/clean-architecture/js/src/usecases/DeleteUser.spec.js.ejs +47 -0
- package/templates/clean-architecture/js/src/usecases/GetAllUsers.js +12 -0
- package/templates/clean-architecture/js/src/usecases/GetAllUsers.spec.js.ejs +61 -0
- package/templates/clean-architecture/js/src/usecases/UpdateUser.js.ejs +11 -0
- package/templates/clean-architecture/js/src/usecases/UpdateUser.spec.js.ejs +48 -0
- package/templates/clean-architecture/js/src/utils/errorMessages.js +14 -0
- package/templates/clean-architecture/js/src/utils/httpCodes.js +9 -0
- package/templates/clean-architecture/ts/src/config/env.ts.ejs +46 -0
- package/templates/clean-architecture/ts/src/config/swagger.ts.ejs +6 -0
- package/templates/clean-architecture/ts/src/domain/user.ts.ejs +9 -0
- package/templates/clean-architecture/ts/src/errors/ApiError.ts +15 -0
- package/templates/clean-architecture/ts/src/errors/BadRequestError.spec.ts.ejs +22 -0
- package/templates/clean-architecture/ts/src/errors/BadRequestError.ts +9 -0
- package/templates/clean-architecture/ts/src/errors/NotFoundError.spec.ts.ejs +22 -0
- package/templates/clean-architecture/ts/src/errors/NotFoundError.ts +9 -0
- package/templates/clean-architecture/ts/src/index.ts.ejs +144 -0
- package/templates/clean-architecture/ts/src/infrastructure/log/logger.spec.ts.ejs +63 -0
- package/templates/clean-architecture/ts/src/infrastructure/log/logger.ts +36 -0
- package/templates/clean-architecture/ts/src/infrastructure/repositories/UserRepository.spec.ts.ejs +175 -0
- package/templates/clean-architecture/ts/src/infrastructure/repositories/userRepository.ts.ejs +125 -0
- package/templates/clean-architecture/ts/src/interfaces/controllers/userController.spec.ts.ejs +331 -0
- package/templates/clean-architecture/ts/src/interfaces/controllers/userController.ts.ejs +208 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/context.spec.ts.ejs +32 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/context.ts.ejs +17 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/index.ts.ejs +3 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/resolvers/index.ts.ejs +4 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/resolvers/user.resolvers.spec.ts.ejs +68 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/resolvers/user.resolvers.ts.ejs +29 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/typeDefs/index.ts.ejs +4 -0
- package/templates/clean-architecture/ts/src/interfaces/graphql/typeDefs/user.types.ts.ejs +17 -0
- package/templates/clean-architecture/ts/src/interfaces/routes/userRoutes.spec.ts.ejs +40 -0
- package/templates/clean-architecture/ts/src/interfaces/routes/userRoutes.ts.ejs +18 -0
- package/templates/clean-architecture/ts/src/usecases/createUser.spec.ts.ejs +51 -0
- package/templates/clean-architecture/ts/src/usecases/createUser.ts.ejs +11 -0
- package/templates/clean-architecture/ts/src/usecases/deleteUser.spec.ts.ejs +47 -0
- package/templates/clean-architecture/ts/src/usecases/deleteUser.ts +9 -0
- package/templates/clean-architecture/ts/src/usecases/getAllUsers.spec.ts.ejs +63 -0
- package/templates/clean-architecture/ts/src/usecases/getAllUsers.ts +10 -0
- package/templates/clean-architecture/ts/src/usecases/updateUser.spec.ts.ejs +48 -0
- package/templates/clean-architecture/ts/src/usecases/updateUser.ts.ejs +10 -0
- package/templates/clean-architecture/ts/src/utils/errorMessages.ts +12 -0
- package/templates/clean-architecture/ts/src/utils/errorMiddleware.ts.ejs +27 -0
- package/templates/clean-architecture/ts/src/utils/httpCodes.ts +7 -0
- package/templates/common/.cursorrules.ejs +60 -0
- package/templates/common/.dockerignore +12 -0
- package/templates/common/.env.example.ejs +60 -0
- package/templates/common/.gitattributes +46 -0
- package/templates/common/.gitlab-ci.yml.ejs +86 -0
- package/templates/common/.lintstagedrc +6 -0
- package/templates/common/.prettierrc +7 -0
- package/templates/common/.snyk.ejs +45 -0
- package/templates/common/Dockerfile +73 -0
- package/templates/common/Jenkinsfile.ejs +87 -0
- package/templates/common/README.md.ejs +148 -0
- package/templates/common/_github/workflows/ci.yml.ejs +46 -0
- package/templates/common/_github/workflows/security.yml.ejs +36 -0
- package/templates/common/_gitignore +5 -0
- package/templates/common/_husky/pre-commit +4 -0
- package/templates/common/caching/clean/js/CreateUser.js.ejs +29 -0
- package/templates/common/caching/clean/js/DeleteUser.js.ejs +27 -0
- package/templates/common/caching/clean/js/GetAllUsers.js.ejs +37 -0
- package/templates/common/caching/clean/js/UpdateUser.js.ejs +27 -0
- package/templates/common/caching/clean/ts/createUser.ts.ejs +27 -0
- package/templates/common/caching/clean/ts/deleteUser.ts.ejs +24 -0
- package/templates/common/caching/clean/ts/getAllUsers.ts.ejs +34 -0
- package/templates/common/caching/clean/ts/updateUser.ts.ejs +25 -0
- package/templates/common/caching/js/memoryCache.js.ejs +60 -0
- package/templates/common/caching/js/memoryCache.spec.js.ejs +101 -0
- package/templates/common/caching/js/redisClient.js.ejs +75 -0
- package/templates/common/caching/js/redisClient.spec.js.ejs +147 -0
- package/templates/common/caching/ts/memoryCache.spec.ts.ejs +102 -0
- package/templates/common/caching/ts/memoryCache.ts.ejs +73 -0
- package/templates/common/caching/ts/redisClient.spec.ts.ejs +157 -0
- package/templates/common/caching/ts/redisClient.ts.ejs +89 -0
- package/templates/common/database/js/database.js.ejs +19 -0
- package/templates/common/database/js/database.spec.js.ejs +56 -0
- package/templates/common/database/js/models/User.js.ejs +91 -0
- package/templates/common/database/js/models/User.js.mongoose.ejs +35 -0
- package/templates/common/database/js/models/User.spec.js.ejs +94 -0
- package/templates/common/database/js/mongoose.js.ejs +33 -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/database.ts.ejs +21 -0
- package/templates/common/database/ts/models/User.spec.ts.ejs +100 -0
- package/templates/common/database/ts/models/User.ts.ejs +102 -0
- package/templates/common/database/ts/models/User.ts.mongoose.ejs +34 -0
- package/templates/common/database/ts/mongoose.spec.ts.ejs +42 -0
- package/templates/common/database/ts/mongoose.ts.ejs +28 -0
- package/templates/common/docker-compose.yml.ejs +159 -0
- package/templates/common/ecosystem.config.js.ejs +40 -0
- package/templates/common/eslint.config.mjs.ejs +77 -0
- package/templates/common/health/js/healthRoute.js.ejs +50 -0
- 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/health/ts/healthRoute.ts.ejs +49 -0
- package/templates/common/jest.config.js.ejs +32 -0
- package/templates/common/jest.e2e.config.js.ejs +8 -0
- package/templates/common/kafka/js/config/kafka.js +9 -0
- package/templates/common/kafka/js/config/kafka.spec.js.ejs +27 -0
- package/templates/common/kafka/js/messaging/baseConsumer.js.ejs +30 -0
- package/templates/common/kafka/js/messaging/baseConsumer.spec.js.ejs +58 -0
- package/templates/common/kafka/js/messaging/userEventSchema.js.ejs +12 -0
- package/templates/common/kafka/js/messaging/userEventSchema.spec.js.ejs +27 -0
- package/templates/common/kafka/js/messaging/welcomeEmailConsumer.js.ejs +44 -0
- package/templates/common/kafka/js/messaging/welcomeEmailConsumer.spec.js.ejs +86 -0
- package/templates/common/kafka/js/services/kafkaService.js.ejs +93 -0
- package/templates/common/kafka/js/services/kafkaService.spec.js.ejs +106 -0
- package/templates/common/kafka/js/utils/kafkaEvents.js.ejs +7 -0
- package/templates/common/kafka/ts/config/kafka.spec.ts.ejs +27 -0
- package/templates/common/kafka/ts/config/kafka.ts +7 -0
- package/templates/common/kafka/ts/messaging/baseConsumer.spec.ts.ejs +50 -0
- package/templates/common/kafka/ts/messaging/baseConsumer.ts.ejs +27 -0
- package/templates/common/kafka/ts/messaging/userEventSchema.spec.ts.ejs +51 -0
- package/templates/common/kafka/ts/messaging/userEventSchema.ts.ejs +12 -0
- package/templates/common/kafka/ts/messaging/welcomeEmailConsumer.spec.ts.ejs +86 -0
- package/templates/common/kafka/ts/messaging/welcomeEmailConsumer.ts.ejs +38 -0
- package/templates/common/kafka/ts/services/kafkaService.spec.ts.ejs +81 -0
- package/templates/common/kafka/ts/services/kafkaService.ts.ejs +95 -0
- package/templates/common/kafka/ts/utils/kafkaEvents.ts.ejs +5 -0
- package/templates/common/migrate-mongo-config.js.ejs +31 -0
- package/templates/common/migrations/init.js.ejs +23 -0
- package/templates/common/package.json.ejs +137 -0
- package/templates/common/prompts/add-feature.md.ejs +26 -0
- package/templates/common/prompts/project-context.md.ejs +43 -0
- package/templates/common/prompts/troubleshoot.md.ejs +28 -0
- package/templates/common/public/css/style.css +147 -0
- package/templates/common/scripts/run-e2e.js.ejs +63 -0
- package/templates/common/shutdown/js/gracefulShutdown.js.ejs +65 -0
- package/templates/common/shutdown/js/gracefulShutdown.spec.js.ejs +149 -0
- package/templates/common/shutdown/ts/gracefulShutdown.spec.ts.ejs +179 -0
- package/templates/common/shutdown/ts/gracefulShutdown.ts.ejs +59 -0
- package/templates/common/sonar-project.properties.ejs +27 -0
- package/templates/common/src/config/auth.js.ejs +19 -0
- package/templates/common/src/config/auth.ts.ejs +19 -0
- package/templates/common/src/controllers/authController.js.ejs +101 -0
- package/templates/common/src/controllers/authController.ts.ejs +101 -0
- package/templates/common/src/middleware/auth.js.ejs +20 -0
- package/templates/common/src/middleware/auth.ts.ejs +25 -0
- package/templates/common/src/middleware/upload.js.ejs +31 -0
- package/templates/common/src/middleware/upload.ts.ejs +32 -0
- package/templates/common/src/routes/authRoutes.js.ejs +20 -0
- package/templates/common/src/routes/authRoutes.ts.ejs +20 -0
- package/templates/common/src/tests/e2e/e2e.users.test.js.ejs +120 -0
- package/templates/common/src/tests/e2e/e2e.users.test.ts.ejs +120 -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/swagger.yml.ejs +118 -0
- package/templates/common/tsconfig.json +23 -0
- package/templates/common/views/ejs/index.ejs +55 -0
- package/templates/common/views/pug/index.pug +40 -0
- package/templates/db/mysql/V1__Initial_Setup.sql.ejs +10 -0
- package/templates/db/postgres/V1__Initial_Setup.sql.ejs +10 -0
- package/templates/mvc/js/src/config/env.js.ejs +46 -0
- package/templates/mvc/js/src/config/swagger.js.ejs +6 -0
- package/templates/mvc/js/src/controllers/userController.js.ejs +288 -0
- package/templates/mvc/js/src/controllers/userController.spec.js.ejs +481 -0
- package/templates/mvc/js/src/errors/ApiError.js +14 -0
- package/templates/mvc/js/src/errors/BadRequestError.js +11 -0
- package/templates/mvc/js/src/errors/BadRequestError.spec.js.ejs +22 -0
- package/templates/mvc/js/src/errors/NotFoundError.js +11 -0
- package/templates/mvc/js/src/errors/NotFoundError.spec.js.ejs +22 -0
- package/templates/mvc/js/src/graphql/context.js.ejs +7 -0
- package/templates/mvc/js/src/graphql/context.spec.js.ejs +29 -0
- package/templates/mvc/js/src/graphql/index.js.ejs +5 -0
- package/templates/mvc/js/src/graphql/resolvers/index.js.ejs +6 -0
- package/templates/mvc/js/src/graphql/resolvers/user.resolvers.js.ejs +25 -0
- package/templates/mvc/js/src/graphql/resolvers/user.resolvers.spec.js.ejs +64 -0
- package/templates/mvc/js/src/graphql/typeDefs/index.js.ejs +6 -0
- package/templates/mvc/js/src/graphql/typeDefs/user.types.js.ejs +19 -0
- package/templates/mvc/js/src/index.js.ejs +141 -0
- package/templates/mvc/js/src/routes/api.js.ejs +15 -0
- package/templates/mvc/js/src/routes/api.spec.js.ejs +41 -0
- package/templates/mvc/js/src/utils/errorMessages.js +14 -0
- package/templates/mvc/js/src/utils/errorMiddleware.js +29 -0
- package/templates/mvc/js/src/utils/httpCodes.js +9 -0
- package/templates/mvc/js/src/utils/logger.js +40 -0
- package/templates/mvc/js/src/utils/logger.spec.js.ejs +63 -0
- package/templates/mvc/ts/src/config/env.ts.ejs +45 -0
- package/templates/mvc/ts/src/config/swagger.ts.ejs +6 -0
- package/templates/mvc/ts/src/controllers/userController.spec.ts.ejs +481 -0
- package/templates/mvc/ts/src/controllers/userController.ts.ejs +292 -0
- package/templates/mvc/ts/src/errors/ApiError.ts +15 -0
- package/templates/mvc/ts/src/errors/BadRequestError.spec.ts.ejs +22 -0
- package/templates/mvc/ts/src/errors/BadRequestError.ts +9 -0
- package/templates/mvc/ts/src/errors/NotFoundError.spec.ts.ejs +27 -0
- package/templates/mvc/ts/src/errors/NotFoundError.ts +9 -0
- package/templates/mvc/ts/src/graphql/context.spec.ts.ejs +30 -0
- package/templates/mvc/ts/src/graphql/context.ts.ejs +12 -0
- package/templates/mvc/ts/src/graphql/index.ts.ejs +3 -0
- package/templates/mvc/ts/src/graphql/resolvers/index.ts.ejs +4 -0
- package/templates/mvc/ts/src/graphql/resolvers/user.resolvers.spec.ts.ejs +68 -0
- package/templates/mvc/ts/src/graphql/resolvers/user.resolvers.ts.ejs +29 -0
- package/templates/mvc/ts/src/graphql/typeDefs/index.ts.ejs +4 -0
- package/templates/mvc/ts/src/graphql/typeDefs/user.types.ts.ejs +17 -0
- package/templates/mvc/ts/src/index.ts.ejs +157 -0
- package/templates/mvc/ts/src/routes/api.spec.ts.ejs +59 -0
- package/templates/mvc/ts/src/routes/api.ts.ejs +17 -0
- package/templates/mvc/ts/src/utils/errorMessages.ts +12 -0
- package/templates/mvc/ts/src/utils/errorMiddleware.ts.ejs +27 -0
- package/templates/mvc/ts/src/utils/httpCodes.ts +7 -0
- package/templates/mvc/ts/src/utils/logger.spec.ts.ejs +63 -0
- package/templates/mvc/ts/src/utils/logger.ts +36 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const { userResolvers } = require('@/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('@/controllers/userController', () => ({
|
|
7
|
+
getUsers: (...args) => mockGetUsers(...args),
|
|
8
|
+
createUser: (...args) => mockCreateUser(...args),
|
|
9
|
+
updateUser: jest.fn().mockImplementation((id, data) => Promise.resolve({ id, ...data })),
|
|
10
|
+
deleteUser: jest.fn().mockImplementation(() => Promise.resolve(true))
|
|
11
|
+
}));
|
|
12
|
+
|
|
13
|
+
describe('User Resolvers', () => {
|
|
14
|
+
afterEach(() => {
|
|
15
|
+
jest.clearAllMocks();
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe('Query.getAllUsers', () => {
|
|
19
|
+
it('should return all users', async () => {
|
|
20
|
+
const result = await userResolvers.Query.getAllUsers();
|
|
21
|
+
expect(result).toEqual([{ id: '1', name: 'John Doe', email: 'john@example.com' }]);
|
|
22
|
+
expect(mockGetUsers).toHaveBeenCalledTimes(1);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('Mutation.createUser', () => {
|
|
27
|
+
it('should create and return a new user', async () => {
|
|
28
|
+
const result = await userResolvers.Mutation.createUser(null, { name: 'Jane', email: 'jane@example.com' });
|
|
29
|
+
expect(result).toEqual({ id: '1', name: 'Jane', email: 'jane@example.com' });
|
|
30
|
+
expect(mockCreateUser).toHaveBeenCalledWith({ name: 'Jane', email: 'jane@example.com' });
|
|
31
|
+
expect(mockCreateUser).toHaveBeenCalledTimes(1);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe('Mutation.updateUser', () => {
|
|
36
|
+
it('should update and return the user', async () => {
|
|
37
|
+
const payload = { name: 'Updated' };
|
|
38
|
+
const result = await userResolvers.Mutation.updateUser(null, { id: '1', ...payload });
|
|
39
|
+
expect(result).toMatchObject(payload);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('Mutation.deleteUser', () => {
|
|
44
|
+
it('should delete and return true', async () => {
|
|
45
|
+
const result = await userResolvers.Mutation.deleteUser(null, { id: '1' });
|
|
46
|
+
expect(result).toBe(true);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
<%_ if (database === 'MongoDB') { -%>
|
|
50
|
+
describe('User.id', () => {
|
|
51
|
+
it('should return parent.id if available', () => {
|
|
52
|
+
const parent = { id: '123' };
|
|
53
|
+
const result = userResolvers.User.id(parent);
|
|
54
|
+
expect(result).toBe('123');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should fallback to parent._id if id is not available', () => {
|
|
58
|
+
const parent = { _id: '456' };
|
|
59
|
+
const result = userResolvers.User.id(parent);
|
|
60
|
+
expect(result).toBe('456');
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
<%_ } -%>
|
|
64
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
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
|
+
`;
|
|
18
|
+
|
|
19
|
+
module.exports = { userTypes };
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
const { env } = require('./config/env');
|
|
2
|
+
const express = require('express');
|
|
3
|
+
const cors = require('cors');
|
|
4
|
+
<%_ if (communication === 'REST APIs' || communication === 'Kafka') { -%>const apiRoutes = require('./routes/api');<%_ } %>
|
|
5
|
+
const healthRoutes = require('./routes/healthRoute');
|
|
6
|
+
<%_ if (communication === 'Kafka') { -%>const { connectKafka, sendMessage } = require('./services/kafkaService');<%_ } -%>
|
|
7
|
+
<%_ if (communication === 'GraphQL') { -%>
|
|
8
|
+
const { ApolloServer } = require('@apollo/server');
|
|
9
|
+
const { expressMiddleware } = require('@as-integrations/express4');
|
|
10
|
+
const { ApolloServerPluginLandingPageLocalDefault } = require('@apollo/server/plugin/landingPage/default');
|
|
11
|
+
const { unwrapResolverError } = require('@apollo/server/errors');
|
|
12
|
+
const { ApiError } = require('./errors/ApiError');
|
|
13
|
+
const { typeDefs, resolvers } = require('./graphql');
|
|
14
|
+
const { gqlContext } = require('./graphql/context');
|
|
15
|
+
<% } %>
|
|
16
|
+
<%_ if (communication === 'REST APIs' || communication === 'Kafka') { -%>
|
|
17
|
+
const swaggerUi = require('swagger-ui-express');
|
|
18
|
+
const swaggerSpecs = require('./config/swagger');
|
|
19
|
+
<%_ } -%>
|
|
20
|
+
const setupGracefulShutdown = require('./utils/gracefulShutdown');
|
|
21
|
+
|
|
22
|
+
const app = express();
|
|
23
|
+
const PORT = env.PORT;
|
|
24
|
+
const logger = require('./utils/logger');
|
|
25
|
+
const morgan = require('morgan');
|
|
26
|
+
const { errorMiddleware } = require('./utils/errorMiddleware');
|
|
27
|
+
|
|
28
|
+
app.use(cors());
|
|
29
|
+
app.use(express.json());
|
|
30
|
+
<% if (includeMulter) { %>
|
|
31
|
+
const path = require('path');
|
|
32
|
+
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
|
|
33
|
+
<% } %>
|
|
34
|
+
app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) } }));
|
|
35
|
+
|
|
36
|
+
<%_ if (communication === 'REST APIs' || communication === 'Kafka') { -%>
|
|
37
|
+
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpecs));
|
|
38
|
+
<%_ } -%>
|
|
39
|
+
<%_ if (viewEngine === 'EJS' || viewEngine === 'Pug') { -%>
|
|
40
|
+
// View Engine Setup
|
|
41
|
+
const path = require('path');
|
|
42
|
+
app.set('views', path.join(__dirname, 'views'));
|
|
43
|
+
app.set('view engine', '<%= viewEngine.toLowerCase() %>');
|
|
44
|
+
app.use(express.static(path.join(__dirname, '../public')));<%_ } %>
|
|
45
|
+
<%_ if (communication === 'REST APIs' || communication === 'Kafka') { -%>
|
|
46
|
+
app.use('/api', apiRoutes);
|
|
47
|
+
<%_ } -%><% if (viewEngine && viewEngine !== 'None') { -%>
|
|
48
|
+
app.get('/', (req, res) => {
|
|
49
|
+
res.render('index', {
|
|
50
|
+
projectName: 'NodeJS Service',
|
|
51
|
+
architecture: 'MVC',
|
|
52
|
+
database: '<%= database %>',
|
|
53
|
+
communication: '<%= communication %>'
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
<% } -%>
|
|
57
|
+
app.use('/health', healthRoutes);
|
|
58
|
+
|
|
59
|
+
// Start Server Logic
|
|
60
|
+
const startServer = async () => {
|
|
61
|
+
<%_ if (communication === 'GraphQL') { -%>
|
|
62
|
+
// GraphQL Setup
|
|
63
|
+
const apolloServer = new ApolloServer({
|
|
64
|
+
typeDefs,
|
|
65
|
+
resolvers,
|
|
66
|
+
plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })],
|
|
67
|
+
formatError: (formattedError, error) => {
|
|
68
|
+
const originalError = unwrapResolverError(error);
|
|
69
|
+
if (originalError instanceof ApiError) {
|
|
70
|
+
return {
|
|
71
|
+
...formattedError,
|
|
72
|
+
message: originalError.message,
|
|
73
|
+
extensions: {
|
|
74
|
+
...formattedError.extensions,
|
|
75
|
+
code: originalError.statusCode.toString(),
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
logger.error(`GraphQL Error: ${formattedError.message}`);
|
|
81
|
+
if (originalError && originalError.stack && process.env.NODE_ENV === 'development') {
|
|
82
|
+
logger.error(originalError.stack);
|
|
83
|
+
}
|
|
84
|
+
return formattedError;
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
await apolloServer.start();
|
|
88
|
+
app.use('/graphql', expressMiddleware(apolloServer, { context: gqlContext }));
|
|
89
|
+
<%_ } -%>
|
|
90
|
+
app.use(errorMiddleware);
|
|
91
|
+
const server = app.listen(PORT, () => {
|
|
92
|
+
logger.info(`Server running on port ${PORT}`);
|
|
93
|
+
<%_ if (communication === 'Kafka') { -%>
|
|
94
|
+
connectKafka()
|
|
95
|
+
.then(async () => {
|
|
96
|
+
logger.info('Kafka connected');
|
|
97
|
+
})
|
|
98
|
+
.catch(err => {
|
|
99
|
+
logger.error('Failed to connect to Kafka after retries:', err.message);
|
|
100
|
+
});
|
|
101
|
+
<%_ } -%>
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
setupGracefulShutdown(server);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
<%_ if (database !== 'None') { -%>
|
|
108
|
+
// Database Sync
|
|
109
|
+
<%_ if (database !== 'None') { -%>
|
|
110
|
+
<%_ if (database === 'MongoDB') { -%>
|
|
111
|
+
const connectDB = require('./config/database');
|
|
112
|
+
<%_ } else { -%>
|
|
113
|
+
const sequelize = require('./config/database');
|
|
114
|
+
<%_ } -%>
|
|
115
|
+
<%_ } -%>
|
|
116
|
+
const syncDatabase = async () => {
|
|
117
|
+
let retries = 30;
|
|
118
|
+
while (retries) {
|
|
119
|
+
try {
|
|
120
|
+
<%_ if (database === 'MongoDB') { -%>
|
|
121
|
+
await connectDB();
|
|
122
|
+
<%_ } else { -%>
|
|
123
|
+
await sequelize.sync();
|
|
124
|
+
<%_ } -%>
|
|
125
|
+
logger.info('Database synced');
|
|
126
|
+
// Start Server after DB is ready
|
|
127
|
+
await startServer();
|
|
128
|
+
break;
|
|
129
|
+
} catch (err) {
|
|
130
|
+
logger.error('Database sync failed:', err);
|
|
131
|
+
retries -= 1;
|
|
132
|
+
logger.info(`Retries left: ${retries}. Waiting 5s...`);
|
|
133
|
+
await new Promise(res => setTimeout(res, 5000));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
syncDatabase();
|
|
139
|
+
<%_ } else { -%>
|
|
140
|
+
startServer();
|
|
141
|
+
<%_ } -%>
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const express = require('express');
|
|
2
|
+
const router = express.Router();
|
|
3
|
+
const userController = require('../controllers/userController');
|
|
4
|
+
<% if (auth && auth !== 'None') { %>const { authMiddleware } = require('../middleware/auth');<% } %>
|
|
5
|
+
<% if (includeMulter) { %>const { upload } = require('../middleware/upload');<% } %>
|
|
6
|
+
<% if (auth && auth !== 'None') { %>const authRoutes = require('./authRoutes');<% } %>
|
|
7
|
+
|
|
8
|
+
<% if (auth && auth !== 'None') { %>router.use('/auth', authRoutes);<% } %>
|
|
9
|
+
|
|
10
|
+
router.get('/users', userController.getUsers);
|
|
11
|
+
router.post('/users', <% if (includeMulter) { %>upload.single('image'), <% } %>userController.createUser);
|
|
12
|
+
router.patch('/users/:id', <% if (includeMulter) { %>upload.single('image'), <% } %>userController.updateUser);
|
|
13
|
+
router.delete('/users/:id', userController.deleteUser);
|
|
14
|
+
|
|
15
|
+
module.exports = router;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const request = require('supertest');
|
|
2
|
+
const express = require('express');
|
|
3
|
+
const router = require('@/routes/api');
|
|
4
|
+
|
|
5
|
+
const mockGetUsers = jest.fn().mockImplementation((req, res) => res.status(200).json([{ id: '1', name: 'John Doe' }]));
|
|
6
|
+
const mockCreateUser = jest.fn().mockImplementation((req, res) => res.status(201).json({ id: '1', name: 'Test' }));
|
|
7
|
+
|
|
8
|
+
const mockUpdateUser = jest.fn().mockImplementation((req, res) => res.status(200).json({ id: '1', name: 'Updated' }));
|
|
9
|
+
const mockDeleteUser = jest.fn().mockImplementation((req, res) => res.status(200).json({ message: 'User deleted successfully' }));
|
|
10
|
+
|
|
11
|
+
jest.mock('@/controllers/userController', () => ({
|
|
12
|
+
getUsers: (...args) => mockGetUsers(...args),
|
|
13
|
+
createUser: (...args) => mockCreateUser(...args),
|
|
14
|
+
updateUser: (...args) => mockUpdateUser(...args),
|
|
15
|
+
deleteUser: (...args) => mockDeleteUser(...args)
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
describe('ApiRoutes', () => {
|
|
19
|
+
let app;
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
app = express();
|
|
23
|
+
app.use(express.json());
|
|
24
|
+
app.use('/api', router);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('GET /api/users should call controller.getUsers', async () => {
|
|
28
|
+
await request(app)
|
|
29
|
+
.get('/api/users');
|
|
30
|
+
|
|
31
|
+
expect(mockGetUsers).toHaveBeenCalledTimes(1);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('POST /api/users should call controller.createUser', async () => {
|
|
35
|
+
await request(app)
|
|
36
|
+
.post('/api/users')
|
|
37
|
+
.send({ name: 'Test', email: 'test@example.com' });
|
|
38
|
+
|
|
39
|
+
expect(mockCreateUser).toHaveBeenCalledTimes(1);
|
|
40
|
+
});
|
|
41
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
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
|
+
};
|
|
13
|
+
|
|
14
|
+
module.exports = ERROR_MESSAGES;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const logger = require('./logger');
|
|
2
|
+
const { ApiError } = require('../errors/ApiError');
|
|
3
|
+
const HTTP_STATUS = require('./httpCodes');
|
|
4
|
+
|
|
5
|
+
// eslint-disable-next-line no-unused-vars
|
|
6
|
+
const errorMiddleware = (err, req, res, next) => {
|
|
7
|
+
let error = err;
|
|
8
|
+
|
|
9
|
+
if (!(error instanceof ApiError)) {
|
|
10
|
+
const statusCode = err.statusCode || HTTP_STATUS.INTERNAL_SERVER_ERROR;
|
|
11
|
+
const message = error.message || 'Internal Server Error';
|
|
12
|
+
error = new ApiError(statusCode, message, false, err.stack);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const { statusCode, message } = error;
|
|
16
|
+
|
|
17
|
+
if (statusCode === HTTP_STATUS.INTERNAL_SERVER_ERROR) {
|
|
18
|
+
logger.error(`${statusCode} - ${message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
|
|
19
|
+
logger.error(error.stack || 'No stack trace');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
res.status(statusCode).json({
|
|
23
|
+
statusCode,
|
|
24
|
+
message,
|
|
25
|
+
...(process.env.NODE_ENV === 'development' && { stack: error.stack }),
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
module.exports = { errorMiddleware };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const winston = require('winston');
|
|
2
|
+
require('winston-daily-rotate-file');
|
|
3
|
+
|
|
4
|
+
const logger = winston.createLogger({
|
|
5
|
+
level: 'info',
|
|
6
|
+
format: winston.format.combine(
|
|
7
|
+
winston.format.timestamp(),
|
|
8
|
+
winston.format.json()
|
|
9
|
+
),
|
|
10
|
+
defaultMeta: { service: 'user-service' },
|
|
11
|
+
transports: [
|
|
12
|
+
new winston.transports.DailyRotateFile({
|
|
13
|
+
filename: 'logs/error-%DATE%.log',
|
|
14
|
+
datePattern: 'YYYY-MM-DD',
|
|
15
|
+
zippedArchive: true,
|
|
16
|
+
maxSize: '20m',
|
|
17
|
+
maxFiles: '14d',
|
|
18
|
+
level: 'error',
|
|
19
|
+
}),
|
|
20
|
+
new winston.transports.DailyRotateFile({
|
|
21
|
+
filename: 'logs/combined-%DATE%.log',
|
|
22
|
+
datePattern: 'YYYY-MM-DD',
|
|
23
|
+
zippedArchive: true,
|
|
24
|
+
maxSize: '20m',
|
|
25
|
+
maxFiles: '14d',
|
|
26
|
+
}),
|
|
27
|
+
],
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
//
|
|
31
|
+
// If we're not in production then log to the `console` with the format:
|
|
32
|
+
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
|
|
33
|
+
//
|
|
34
|
+
logger.add(new winston.transports.Console({
|
|
35
|
+
format: process.env.NODE_ENV !== 'production'
|
|
36
|
+
? winston.format.simple()
|
|
37
|
+
: winston.format.json(),
|
|
38
|
+
}));
|
|
39
|
+
|
|
40
|
+
module.exports = logger;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
jest.mock('winston-daily-rotate-file');
|
|
2
|
+
jest.mock('winston', () => {
|
|
3
|
+
const mockLogger = {
|
|
4
|
+
add: jest.fn(),
|
|
5
|
+
info: jest.fn(),
|
|
6
|
+
error: jest.fn(),
|
|
7
|
+
warn: jest.fn()
|
|
8
|
+
};
|
|
9
|
+
const format = {
|
|
10
|
+
combine: jest.fn(),
|
|
11
|
+
timestamp: jest.fn(),
|
|
12
|
+
json: jest.fn(),
|
|
13
|
+
simple: jest.fn()
|
|
14
|
+
};
|
|
15
|
+
const transports = {
|
|
16
|
+
Console: jest.fn(),
|
|
17
|
+
DailyRotateFile: jest.fn()
|
|
18
|
+
};
|
|
19
|
+
return {
|
|
20
|
+
format,
|
|
21
|
+
transports,
|
|
22
|
+
createLogger: jest.fn().mockReturnValue(mockLogger)
|
|
23
|
+
};
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
<% if (architecture === 'MVC') { -%>
|
|
27
|
+
const logger = require('@/utils/logger');
|
|
28
|
+
<% } else { -%>
|
|
29
|
+
const logger = require('@/infrastructure/log/logger');
|
|
30
|
+
<% } -%>
|
|
31
|
+
|
|
32
|
+
describe('Logger', () => {
|
|
33
|
+
it('should export a logger instance', () => {
|
|
34
|
+
expect(logger).toBeDefined();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('should have info method', () => {
|
|
38
|
+
expect(typeof logger.info).toBe('function');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('should have error method', () => {
|
|
42
|
+
expect(typeof logger.error).toBe('function');
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('should call info', () => {
|
|
46
|
+
logger.info('test message');
|
|
47
|
+
expect(logger.info).toHaveBeenCalledWith('test message');
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('should call error', () => {
|
|
51
|
+
logger.error('test error');
|
|
52
|
+
expect(logger.error).toHaveBeenCalledWith('test error');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('should use JSON format in production environment', () => {
|
|
56
|
+
const winston = require('winston');
|
|
57
|
+
jest.resetModules();
|
|
58
|
+
process.env.NODE_ENV = 'production';
|
|
59
|
+
require('@/utils/logger');
|
|
60
|
+
expect(winston.format.json).toHaveBeenCalled();
|
|
61
|
+
process.env.NODE_ENV = 'test';
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import dotenv from 'dotenv';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import logger from '@/utils/logger';
|
|
4
|
+
|
|
5
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
6
|
+
dotenv.config();
|
|
7
|
+
}
|
|
8
|
+
const envSchema = z.object({
|
|
9
|
+
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
|
|
10
|
+
PORT: z.string().transform(Number).default('3000'),
|
|
11
|
+
<%_ if (database !== 'None') { -%>
|
|
12
|
+
DB_HOST: z.string(),
|
|
13
|
+
<%_ if (database === 'MySQL') { -%>
|
|
14
|
+
DB_USER: z.string(),
|
|
15
|
+
DB_PASSWORD: z.string(),
|
|
16
|
+
DB_NAME: z.string(),
|
|
17
|
+
DB_PORT: z.string().transform(Number),
|
|
18
|
+
<%_ } else if (database === 'PostgreSQL') { -%>
|
|
19
|
+
DB_USER: z.string(),
|
|
20
|
+
DB_PASSWORD: z.string(),
|
|
21
|
+
DB_NAME: z.string(),
|
|
22
|
+
DB_PORT: z.string().transform(Number),
|
|
23
|
+
<%_ } else if (database === 'MongoDB') { -%>
|
|
24
|
+
DB_NAME: z.string(),
|
|
25
|
+
DB_PORT: z.string().transform(Number),
|
|
26
|
+
<%_ } -%>
|
|
27
|
+
<%_ } -%>
|
|
28
|
+
<%_ if (caching === 'Redis') { -%>
|
|
29
|
+
REDIS_HOST: z.string(),
|
|
30
|
+
REDIS_PORT: z.string().transform(Number),
|
|
31
|
+
REDIS_PASSWORD: z.string().optional(),
|
|
32
|
+
<%_ } -%>
|
|
33
|
+
<%_ if (communication === 'Kafka') { -%>
|
|
34
|
+
KAFKA_BROKER: z.string(),
|
|
35
|
+
<%_ } -%>
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const _env = envSchema.safeParse(process.env);
|
|
39
|
+
|
|
40
|
+
if (!_env.success) {
|
|
41
|
+
logger.error('❌ Invalid environment variables:', _env.error.format());
|
|
42
|
+
process.exit(1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const env = _env.data;
|