-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathutils.generator.js
More file actions
267 lines (232 loc) · 7.4 KB
/
utils.generator.js
File metadata and controls
267 lines (232 loc) · 7.4 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
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
264
265
266
267
// Copyright IBM Corp. and LoopBack contributors 2019,2020. All Rights Reserved.
// Node module: @loopback/cli
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
const ast = require('ts-morph');
const path = require('path');
const tsquery = require('../../lib/ast-helper');
const utils = require('../../lib/utils');
exports.relationType = {
belongsTo: 'belongsTo',
hasMany: 'hasMany',
hasManyThrough: 'hasManyThrough',
hasOne: 'hasOne',
referencesMany: 'referencesMany',
};
class AstLoopBackProject extends ast.Project {
constructor() {
super({
manipulationSettings: {
indentationText: ast.IndentationText.TwoSpaces,
insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: false,
newLineKind: ast.NewLineKind.LineFeed,
quoteKind: ast.QuoteKind.Single,
},
});
}
}
exports.AstLoopBackProject = AstLoopBackProject;
exports.getModelPrimaryKeyProperty = async function (fs, modelDir, modelName) {
const modelFile = path.join(modelDir, utils.getModelFileName(modelName));
const fileContent = await fs.read(modelFile, {});
return tsquery.getIdFromModel(fileContent);
};
exports.getModelPropertyType = function (modelDir, modelName, propertyName) {
const project = new this.AstLoopBackProject();
const modelFile = path.join(modelDir, utils.getModelFileName(modelName));
const sf = project.addSourceFileAtPath(modelFile);
const co = this.getClassObj(sf, modelName);
return this.getPropertyType(co, propertyName);
};
exports.addFileToProject = function (project, dir, modelName) {
const fileName = path.resolve(dir, utils.getModelFileName(modelName));
return project.addSourceFileAtPath(fileName);
};
exports.getClassObj = function (fileName, modelName) {
return fileName.getClassOrThrow(modelName);
};
exports.getClassConstructor = function (classObj) {
return classObj.getConstructors()[0];
};
exports.addExportController = async function (
generator,
fileName,
controllerClassName,
controllerFileName,
) {
const project = new this.AstLoopBackProject();
let pFile;
const exportDeclaration = {
kind: ast.StructureKind.ExportDeclaration,
moduleSpecifier: './' + controllerFileName,
};
if (generator.fs.exists(fileName)) {
pFile = project.addSourceFileAtPath(fileName);
// Exported declarations is now a `Map<string, Declaration[]>`
const exportedDeclarations = pFile.getExportedDeclarations();
for (const declarations of exportedDeclarations.values()) {
for (const declaration of declarations) {
if (
ast.Node.isClassDeclaration(declaration) &&
controllerClassName === declaration.getName()
) {
return;
}
}
}
pFile.addExportDeclaration(exportDeclaration);
} else {
pFile = project.createSourceFile(fileName, {
statements: [exportDeclaration],
});
}
await pFile.save();
};
/**
* Validate if property exist in class.
*
* @param {classObj}
* @param {propertyName} string
*
* @returns bool true on success, false on failure.
*/
exports.doesPropertyExist = function (classObj, propertyName) {
return classObj
.getProperties()
.map(x => x.getName())
.includes(propertyName);
};
exports.doesRelationExist = function (classObj, propertyName, options = {}) {
const force = options.force;
if (this.doesPropertyExist(classObj, propertyName)) {
// If the property is decorated by `@property()`,
// turn it to be a relational property decorated by `@belongsTo()`
const decorators = classObj.getProperty(propertyName).getDecorators();
const hasPropertyDecorator =
decorators.length > 0 && decorators[0].getName() === 'property';
if (!force) {
// If it's already decorated by a relational decorator,
// throw error
if (!hasPropertyDecorator) {
throw new Error(
'relational property ' +
propertyName +
' already exist in the model ' +
classObj.getName() +
' Use --force to overwrite it',
);
}
}
this.deleteProperty(classObj.getProperty(propertyName));
}
};
/**
* Get property type in class.
*
* @param {classObj}
* @param {propertyName} string
*
* @returns string
*/
exports.getPropertyType = function (classObj, propertyName) {
return classObj.getProperty(propertyName).getType().getText();
};
/**
* Validate if property with specific type exist in class.
*
* @param {classObj}
* @param {propertyName} string
* @param {propertyType} string
*
* @returns bool true on success, false on failure.
*/
exports.isValidPropertyType = function (classObj, propertyName, propertyType) {
return this.getPropertyType(classObj, propertyName) === propertyType;
};
exports.doesParameterExist = function (classConstructor, parameterName) {
return classConstructor
.getParameters()
.map(x => x.getName())
.includes(parameterName);
};
exports.addForeignKey = function (foreignKey, sourceModelPrimaryKeyType) {
return {
decorators: [
{
name: 'property',
arguments: ["{\n type : '" + sourceModelPrimaryKeyType + "',\n}"],
},
],
name: foreignKey + '?',
type: sourceModelPrimaryKeyType,
};
};
exports.addProperty = function (classOBj, property) {
classOBj.insertProperty(this.getPropertiesCount(classOBj), property);
classOBj.insertText(this.getPropertyStartPos(classOBj), '\n');
};
exports.deleteProperty = function (propObj) {
propObj.remove();
};
exports.getPropertiesCount = function (classObj) {
return classObj.getProperties().length;
};
exports.getPropertyStartPos = function (classObj) {
return classObj
.getChildSyntaxList()
.getChildAtIndex(this.getPropertiesCount(classObj) - 1)
.getPos();
};
exports.addRequiredImports = function (sourceFile, imports) {
for (const currentImport of imports) {
this.addCurrentImport(sourceFile, currentImport);
}
};
exports.getRequiredImports = function (targetModel, relationType, sourceModel) {
const requiredImports = [
{
name: relationType,
module: '@loopback/repository',
},
];
if (sourceModel !== targetModel) {
requiredImports.push({
name: targetModel,
module: './' + utils.toFileName(targetModel) + '.model',
});
}
return requiredImports;
};
exports.addCurrentImport = function (sourceFile, currentImport) {
if (!this.doesModuleExists(sourceFile, currentImport.module)) {
sourceFile.addImportDeclaration({
moduleSpecifier: currentImport.module,
});
}
if (!this.doesImportExistInModule(sourceFile, currentImport)) {
sourceFile
.getImportDeclarationOrThrow(currentImport.module)
.addNamedImport(currentImport.name);
}
};
exports.doesModuleExists = function (sourceFile, moduleName) {
return sourceFile.getImportDeclaration(moduleName);
};
exports.doesImportExistInModule = function (sourceFile, currentImport) {
let identicalImport;
const relevantImports = this.getNamedImportsFromModule(
sourceFile,
currentImport.module,
);
if (relevantImports.length > 0) {
identicalImport = relevantImports[0]
.getNamedImports()
.filter(imp => imp.getName() === currentImport.name);
}
return identicalImport && identicalImport.length > 0;
};
exports.getNamedImportsFromModule = function (sourceFile, moduleName) {
const allImports = sourceFile.getImportDeclarations();
return allImports.filter(imp => imp.getModuleSpecifierValue() === moduleName);
};