-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
executable file
·263 lines (199 loc) · 9.1 KB
/
index.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/env node
const pjson = require(__dirname + '/package.json');
const prog = require('caporal');
const fs = require('fs');
const path = require('path');
const generate = require('./lib/generator');
const TypeHelper = require('./lib/TypeHelper');
let version = pjson ? pjson.version : '<unknown version>';
prog
.version(version)
.argument('<name>', 'Name of the model or module')
.option('-a', 'Generate all (Module + Controller + Service + Repository + Model)')
.option('--all', 'Generate all (Module + Controller + Service + Repository + Model)')
.option('-m', 'Generate a Module')
.option('--module', 'Generate a Module')
.option('-r', 'Generate a Repository for the model')
.option('--repo', 'Generate a Repository for the model')
.option('--repository', 'Generate a Repository for the model')
.option('-d', 'Generate the model file')
.option('--model [...prop:type]', 'Generate the model file (and optional model definition)')
.option('--model-class <name>', 'Specify a custom class name for the model')
.option('--model-dir <dir>', 'Specify a subdirectory to put the model in (ie. \'models\')')
.option('--model-base-class <class>', 'Specify a base class that your model should extend from')
.option('--model-base-dir <dir>', 'Specify the import location for the base class model')
.option('-c', 'Generate a Controller for the model')
.option('--controller', 'Generate a Controller for the model')
.option('-s', 'Generate a Service for the model')
.option('--service', 'Generate a Service for the model')
// make interface?
.option('--crud', 'Generates CRUD actions within the Controller and Service')
// add prefix/subdir to generate in
.option('-p <prefix>', 'Specify root/prefix dir to generate in')
.option('--prefix <prefix>', 'Specify root/prefix dir to generate in')
// add authentication guards?
.option('--auth', 'CRUD actions will add authentication guards, requiring a logged in user')
.option('--auth-guard-class <name>', 'Name of a custom @(Guard<name>) class to use')
.option('--auth-guard-dir <dir>', 'The location of the custom @Guard class file')
.option('--template-dir <dir>', 'The location of the template files to use')
.option('--no-subdir', 'Don\'t put generated files in <name> subdirectory (only if not using a module)')
.option('--casing <pascal>', 'default = "example.controller.ts", pascal = "ExampleController.ts"')
.action((args, o, logger) => {
console.log(`Running nestjs-gen v${version} generator...`)
// first see if there's a configuration file available, and start with that
const { configFilePath, config } = _findConfig();
if (config) {
console.log(`Using ${configFilePath} settings...`);
if (config["prefix"] && !o.prefix)
o.prefix = config["prefix"];
if (config["modelDir"] && !o.modelDir)
o.modelDir = config["modelDir"];
if (config["templateDir"] && !o.templateDir)
o.templateDir = config["templateDir"];
if (config["noSubdir"] && !o.noSubdir)
o.noSubdir = config["noSubdir"];
if (config["casing"] && !o.casing)
o.casing = config["casing"];
if (config["authGuardClass"] && !o.authGuardClass)
o.authGuardClass = config["authGuardClass"];
if (config["authGuardDir"] && !o.authGuardDir)
o.authGuardDir = config["authGuardDir"];
if (config["modelBaseClass"] && !o.modelBaseClass)
o.modelBaseClass = config["modelBaseClass"];
if (config["modelBaseDir"] && !o.modelBaseDir)
o.modelBaseDir = config["modelBaseDir"];
}
let modelDef = undefined;
// normalize and validate
if (o.p) { o.prefix = o.p };
if (o.a || o.all) { o.all = true };
if (o.m || o.module) { o.module = true };
if (o.r || o.repo || o.repository) { o.repository = true };
if (o.model && typeof o.model == 'string') { modelDef = o.model };
if (o.md || o.model || o.repository) { o.model = true };
if (o.c || o.controller) { o.controller = true };
if (o.s || o.service) { o.service = true };
if (o.all) {
o.module = o.repository = o.model = o.controller = o.service = o.crud = true;
}
o.name = args.name.toLowerCase();
o.nameUpper = _capitalize(args.name);
// set auth guarding params if applicable?
if (o.auth) {
if (!o.authGuardClass)
throw "--auth-guard-class <name> must be specified if using authentication";
if (!o.authGuardDir)
throw "--auth-guard-dir <dir> must be specified if using authentication";
}
if (o.modelBaseClass && !o.modelBaseDir)
throw "Must specificy --model-base-dir <dir> if using a custom --model-base-class";
if (o.modelBaseDir) {
o.modelBaseDir = _ensureTrailingSlash(o.modelBaseDir);
}
// Parse out model property definitions, if given
if (modelDef) {
o.modelProps = TypeHelper.parseModelProps(modelDef);
} else {
o.modelProps = {};
}
////////////////////
// make containing folder for the module, if using, or otherwise the package name
let outPath = path.resolve((o.prefix ? o.prefix : './'));
if (o.module) {
outPath += `/modules/${o.name}`;
} else {
outPath += o.noSubdir ? '' : `/${o.name}`;
}
fs.mkdirSync(outPath, { recursive: true });
// Stage generation of each type of file...
let stagedFiles = [];
// MODEL ?
if (o.model || o.repository || o.crud) {
if (!o.modelClass) {
o.modelClass = o.nameUpper;
if (o.modelClass.charAt(o.modelClass.length-1) === 's') {
o.modelClass = o.modelClass.substr(0, o.modelClass.length-1);
}
}
o.modelClassLower = o.modelClass.toLowerCase();
let outPathModel = outPath;
if (o.modelDir) {
outPathModel += '/' + o.modelDir;
o.modelDir = _ensureTrailingSlash(o.modelDir);
} else {
o.modelDir = '';
}
fs.mkdirSync(outPathModel, { recursive: true });
o.modelFileName = _getFileName(o.modelClass, 'model', o.casing);
let outFile = `${outPathModel}/${o.modelFileName}.ts`;
stagedFiles.push({ type: 'model', outFile });
}
// MODULE ?
if (o.module) {
o.moduleFileName = _getFileName(o.name, 'module', o.casing);
let outFile = `${outPath}/${o.moduleFileName}.ts`;
stagedFiles.push({ type: 'module', outFile });
}
// REPOSITORY ?
if (o.repository) {
o.repositoryName = o.nameUpper + 'Repository';
o.repositoryFileName = _getFileName(o.name, 'repository', o.casing);
let outFile = `${outPath}/${o.repositoryFileName}.ts`;
stagedFiles.push({ type: 'repository', outFile });
} else if (o.crud) {
// use a generic repository
o.repositoryName = `Repository\<${o.modelClass}\>`;
o.repositoryFileName = _getFileName(o.name, 'repository', o.casing);
let outFile = `${outPath}/${o.repositoryFileName}.ts`;
stagedFiles.push({ type: 'repository', outFile });
}
// CONTROLLER ?
if (o.controller || o.crud) {
o.controllerFileName = _getFileName(o.name, 'controller', o.casing);
let outFile = `${outPath}/${o.controllerFileName}.ts`;
stagedFiles.push({ type: 'controller', outFile });
}
// SERVICE ?
if (o.service) {
o.serviceFileName = _getFileName(o.name, 'service', o.casing);
let outFile = `${outPath}/${o.serviceFileName}.ts`;
stagedFiles.push({ type: 'service', outFile });
}
// Actually output the staged files
stagedFiles.forEach(fd => {
generate(fd.type, o, fd.outFile);
});
});
prog.parse(process.argv);
// Utils ------------------------
function _capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function _getFileName(className, type, casing) {
let _default = `${className.toLowerCase()}.${type}`;
return casing ? (casing === 'pascal' ? `${_capitalize(className)}${_capitalize(type)}` : _default) : _default;
}
function _ensureTrailingSlash(str) {
return str.charAt(str.length-1) !== '/' ? (str + '/') : str;
}
// todo: look into parent directories if not found?
function _findConfig() {
let config;
let configFilePath;
function _read(filePath) {
if (fs.existsSync(filePath)) {
let _config = require(filePath);
if (_config['ngen-config']) {
configFilePath = filePath;
return _config['ngen-config'];
}
}
}
// look in tsconfig.app.json?
config = _read(path.resolve("./tsconfig.app.json"));
// look in tsconfig.json?
if (!config) {
config = _read(path.resolve("./tsconfig.json"));
}
return { configFilePath, config };
}