This repository was archived by the owner on Jul 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.js
More file actions
201 lines (157 loc) · 5.54 KB
/
Copy pathcodegen.js
File metadata and controls
201 lines (157 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
const fs = require('node:fs');
const path = require('node:path');
const { getArgs, askQuestion } = require('./codegen-util');
const INDEX_TXT = `export { default } from './apiHandler';
`;
const TYPES_TXT = `// export interface IReqBody {}
// export interface IResBody {}
export interface IResLocals {
userId: number;
}
`;
const PROVIDER_TXT = `import db from '../../utils/db';
//import {} from './types';
const provider = async () => {
return {};
};
export default provider;
`;
const API_HANDLER_TXT = `import { NextFunction, Request, Response } from 'express';
import { AppError, errDef } from '../../utils/errors';
import provider from './provider';
import { IResLocals } from './types';
const handler = async (req: Request, res: Response, next: NextFunction) => {
try {
const { userId } = res.locals as IResLocals;
const result = await provider();
res.status(200).json({ user_id: result });
} catch (error) {
next(error);
}
};
export default handler;
`;
const getTestTxtForHanlder = (name) => `// Mocks
jest.mock('../../../../src/services/${name}/provider', () => jest.fn());
// Imports
import { NextFunction, Request, Response } from 'express';
import handler from '../../../../src/services/${name}/apiHandler';
import provider from '../../../../src/services/${name}/provider';
import { AppError, errDef } from '../../../../src/utils/errors';
const mockedProvider = provider as jest.Mock;
// Tests
describe('Test /src/services/${name}/apiHandler', () => {
let req: Request;
let res: Response;
let next: NextFunction;
const userId = 123;
beforeEach(() => {
req = { body: {} } as unknown as Request;
res = {
locals: { userId },
status: jest.fn().mockReturnThis(),
json: jest.fn(),
sendStatus: jest.fn(),
sendFile: jest.fn(),
} as unknown as Response;
next = jest.fn();
jest.clearAllMocks();
});
// it('should', async () => {});
it('should call next with UserNotFound error when provider returns 0', async () => {
const expectedError = new AppError(errDef[404].UserNotFound);
mockedProvider.mockResolvedValue(0);
// await handler(req, res, next);
// expect(provider).toBeCalledWith();
// expect(res.status).not.toBeCalled();
// expect(res.json).not.toBeCalled();
// expect(next).toBeCalledWith(expectedError);
});
it('should call next with the error when provider throws an error', async () => {
const expectedError = new Error('err');
mockedProvider.mockRejectedValue(expectedError);
// await handler(req, res, next);
// expect(provider).toBeCalledWith();
// expect(res.status).not.toBeCalled();
// expect(res.json).not.toBeCalled();
// expect(next).toBeCalledWith(expectedError);
});
it('should return 200 when provider returns 1', async () => {
mockedProvider.mockResolvedValue(1);
// await handler(req, res, next);
// expect(provider).toBeCalledWith();
// expect(res.status).toBeCalledWith(200);
// expect(res.json).toBeCalledWith(expected);
// expect(next).not.toBeCalled();
});
});
`;
const getTestTxtForProvider = (name) => `// Mocks
jest.mock('../../../../src/utils/db', () => ({ query: jest.fn() }));
// Imports
import provider from '../../../../src/services/${name}/provider';
import db from '../../../../src/utils/db';
const mockedDbQuery = db.query as jest.Mock;
// Tests
describe('Test /src/services/${name}/provider', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return 0', async () => {
// const expected = {};
// const result = await provider();
// expect(db.query).toBeCalledTimes(1);
// expect(db.query).toBeCalledWith(expect.any(String), [arg1]);
// expect(result).toEqual(expected);
});
it('should', async () => {});
});
`;
const writeService = (str, dir, filename) => {
const filePath = path.resolve(__dirname, 'src', 'services', dir, `${filename}.ts`);
const writer = fs.createWriteStream(filePath);
writer.write(str);
writer.end();
};
const writeTest = (str, dir, filename) => {
const filePath = path.resolve(__dirname, 'test', 'unit', 'services', dir, `${filename}.test.ts`);
const writer = fs.createWriteStream(filePath);
writer.write(str);
writer.end();
};
const main = async () => {
console.log('Code generation started...');
try {
let { name } = getArgs();
// Check that the required flags are in
while (!name) {
console.log('Service name is NOT found!');
name = await askQuestion('Service name, plz?');
}
const dirPath = path.join(__dirname, 'src', 'services', name);
const dirPathTest = path.join(__dirname, 'test', 'unit', 'services', name);
try {
await fs.promises.access(dirPath);
// If exists, ask to overwrite or not
console.log('A component with the given name already exists');
const ans = await askQuestion('Do you want to overwrite it? [y/N]');
if (ans !== 'y' && ans !== 'Y') process.exit(1);
} catch (error) {
// Not existing, create it
console.log(`Creating ${dirPath}`);
await fs.promises.mkdir(dirPath);
console.log(`Creating ${dirPathTest}`);
await fs.promises.mkdir(dirPathTest);
}
writeService(INDEX_TXT, name, 'index');
writeService(TYPES_TXT, name, 'types');
writeService(PROVIDER_TXT, name, 'provider');
writeService(API_HANDLER_TXT, name, 'apiHandler');
writeTest(getTestTxtForHanlder(name), name, 'handler');
writeTest(getTestTxtForProvider(name), name, 'provider');
console.log(`Service "${name}" has been successfully created`);
} catch (err) {
console.error(err);
}
};
main();