-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli.js
238 lines (207 loc) · 7.48 KB
/
cli.js
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const chalk = require('chalk');
const debug = require('debug')('cli');
const yargs = require('yargs/yargs');
const fs = require('fs');
const path = require('path');
const {pascalCase} = require('change-case');
const {
execute,
isLoopBackApp,
updateFile,
addCacheDecorator,
addImport,
getControllerNames,
kebabCase,
log,
modifySpecs,
filterSpec,
} = require('./utils');
const loadSpecs = require('./loadSpecs');
module.exports = async () => {
let {
redisDS,
cacheTTL,
specURL,
prefix,
config,
openapi,
exclude,
readonly,
} = yargs(process.argv.slice(2)).argv;
if(config && typeof config === 'string') {
config = JSON.parse(config);
redisDS = config.redisDS;
cacheTTL = config.cacheTTL;
specURL = config.specURL;
prefix = config.prefix;
include = config.include;
exclude = config.exclude;
readonly = config.readonly;
}
if(openapi && typeof openapi === 'string') {
openapi = JSON.parse(openapi);
specURL = openapi.url;
prefix = openapi.prefix;
}
if (prefix) {
prefix = prefix.replace(/\w+/g, w => w[0].toUpperCase() + w.slice(1).toLowerCase());
}
const invokedFrom = process.cwd();
const modelConfigs = JSON.stringify(require('./model-config.json'));
const package = require(`${invokedFrom}/package.json`);
if (exclude && include) throw Error('We cannot have include and exclude at the same time.');
log(chalk.blue('Confirming if this is a LoopBack 4 project.'));
if (!isLoopBackApp(package)) throw Error('Not a loopback project');
log(chalk.bold(chalk.green('OK.')));
let specs = await loadSpecs(specURL, invokedFrom);
if (!specs) throw Error('No specs received');
let includingList = [];
let excludingList = [];
let includings = [];
let excludings = [];
if (exclude) {
excludings = exclude.split(',');
}
if (include) {
includings = include.split(',');
}
includings.forEach(including => {
if (including.includes(':')) {
const splitedInclude = including.split(':');
const temp = {};
if (splitedInclude[0] === '*') {
temp[splitedInclude[1]] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
includingList.push(temp);
} else {
temp[splitedInclude[1]] = [splitedInclude[0]];
includingList.push(temp);
}
}
});
excludings.forEach(excluding => {
if (excluding.includes(':')) {
const splitedExclude = excluding.split(':');
const temp = {};
if (splitedExclude[0] === '*') {
temp[splitedExclude[1]] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
excludingList.push(temp);
} else {
temp[splitedExclude[1]] = [splitedExclude[0]];
excludingList.push(temp);
}
}
});
const filteredSpec = filterSpec(specs, readonly, excludingList, includingList);
let modifiedSpecs = filteredSpec;
if (prefix) {
modifiedSpecs = modifySpecs(modifiedSpecs, prefix);
}
const controllerNames = getControllerNames(modifiedSpecs, prefix);
log(chalk.blue('Confirming if openapi routes are in place...'));
controllerNames.forEach(controllerName => {
const controllerPath = `${invokedFrom}/src/controllers/${controllerName}.controller.ts`;
if (!fs.existsSync(controllerPath)) {
throw Error('Please run lb4 openapi before this.');
}
});
log(chalk.bold(chalk.green('OK.')));
const datasource = kebabCase(redisDS);
log(chalk.blue('Confirming if datasource is generated...'));
const datasourcePath = `${invokedFrom}/src/datasources/${datasource}.datasource.ts`;
if (!fs.existsSync(datasourcePath)) {
throw Error('Please generate the datasource first.');
}
log(chalk.bold(chalk.green('OK.')));
try {
const deps = package.dependencies;
const pkg = '@aaqilniz/rest-cache';
if (!deps[pkg]) {
await execute(`npm i ${pkg}`, `Installing ${pkg}`);
}
const modelPath = `${invokedFrom}/src/models/cache.model.ts`;
if (!fs.existsSync(modelPath)) {
await execute(
`lb4 model -c '${modelConfigs}' --yes`,
'Creating cache model'
);
}
const repoPath = `${invokedFrom}/src/repositories/cache.repository.ts`;
if (!fs.existsSync(repoPath)) {
await execute(
`lb4 repository -c '{"name":"Cache", "datasource":"${redisDS}", "model":"Cache", "repositoryBaseClass":"DefaultKeyValueRepository"}' --yes`,
'Creating cache repository'
);
}
const providerDir = `${invokedFrom}/src/providers`;
if (!fs.existsSync(providerDir)) fs.mkdirSync(providerDir);
const providerPath = `${invokedFrom}/src/providers/cache-strategy.provider.ts`;
if (!fs.existsSync(providerPath)) {
log(chalk.blue('Creating cache provider.'));
fs.copyFileSync(path.join(__dirname, './text-codes/cache-strategy.provider.txt'), providerPath);
log(chalk.bold(chalk.green('OK.')));
}
addImport(providerPath, `import {${pascalCase(redisDS)}DataSource} from '../datasources';`);
const redisToLowerCase = redisDS.toLowerCase();
updateFile(
providerPath,
'/* datasource-injection */',
`@inject('datasources.${redisDS}') private ${redisToLowerCase}: ${pascalCase(redisDS)}DataSource,`
);
updateFile(
providerPath,
'/* datasource-check-and-assignment */',
`if (this.${redisToLowerCase}.name === this.metadata.datasource) {
customRepo = new CustomRepo(this.${redisToLowerCase});
}`
);
const middlewareDir = `${invokedFrom}/src/middleware`;
if (!fs.existsSync(middlewareDir)) fs.mkdirSync(middlewareDir);
const middlewarePath = `${invokedFrom}/src/middleware/cache.middleware.ts`;
if (!fs.existsSync(middlewarePath)) {
log(chalk.blue('Creating cache middleware.'));
fs.copyFileSync(path.join(__dirname, './text-codes/cache.middleware.txt'), middlewarePath);
log(chalk.bold(chalk.green('OK.')));
}
log(chalk.blue('Adding imports to application.ts'));
const applicationPath = `${invokedFrom}/src/application.ts`;
addImport(applicationPath, 'import {CacheBindings, CacheComponent} from \'@aaqilniz/rest-cache\';');
addImport(applicationPath, 'import {CacheStrategyProvider} from \'./providers/cache-strategy.provider\';');
addImport(applicationPath, 'import {CacheMiddlewareProvider} from \'./middleware/cache.middleware\';');
log(chalk.bold(chalk.green('OK.')));
log(chalk.blue('Updating application.ts'));
updateFile(
applicationPath,
'super(options);',
'this.component(CacheComponent);'
);
updateFile(
applicationPath,
'this.component(CacheComponent);',
'this.bind(CacheBindings.CACHE_STRATEGY).toProvider(CacheStrategyProvider);'
);
updateFile(
applicationPath,
'this.bind(CacheBindings.CACHE_STRATEGY).toProvider(CacheStrategyProvider);',
'this.middleware(CacheMiddlewareProvider);'
);
log(chalk.bold(chalk.green('OK.')));
log(chalk.blue('Adding new imports to controller.ts'));
controllerNames.forEach(controllerName => {
const controllerPath = `${invokedFrom}/src/controllers/${controllerName}.controller.ts`;
addImport(controllerPath, 'import {cache} from \'@aaqilniz/rest-cache\';');
Object.keys(modifiedSpecs.paths).forEach(path => {
addCacheDecorator(
controllerPath,
`@operation('get', '${path}'`,
`@cache('${redisDS}', ${cacheTTL || 60*1000})`,
);
});
});
log(chalk.green('Everything done.'));
process.exit(0);
} catch (error) {
console.log(error);
debug(error);
throw Error('Operation failed.');
}
}