-
-
Notifications
You must be signed in to change notification settings - Fork 526
Expand file tree
/
Copy pathauto-writer.ts
More file actions
242 lines (214 loc) · 9.32 KB
/
auto-writer.ts
File metadata and controls
242 lines (214 loc) · 9.32 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
import fs from "fs";
import _ from "lodash";
import path from "path";
import util from "util";
import { FKSpec, TableData } from ".";
import { AutoOptions, CaseFileOption, CaseOption, LangOption, makeIndent, makeTableName, pluralize, qNameSplit, recase, Relation } from "./types";
const mkdirp = require('mkdirp');
/** Writes text into files from TableData.text, and writes init-models */
export class AutoWriter {
tableText: { [name: string]: string };
foreignKeys: { [tableName: string]: { [fieldName: string]: FKSpec } };
relations: Relation[];
space: string[];
options: {
caseFile?: CaseFileOption;
caseModel?: CaseOption;
caseModelPrefix?: CaseOption;
caseModelSuffix?: CaseOption;
caseProp?: CaseOption;
directory: string;
lang?: LangOption;
noAlias?: boolean;
noInitModels?: boolean;
noWrite?: boolean;
singularize?: boolean;
useDefine?: boolean;
spaces?: boolean;
indentation?: number;
};
constructor(tableData: TableData, options: AutoOptions) {
this.tableText = tableData.text as { [name: string]: string };
this.foreignKeys = tableData.foreignKeys;
this.relations = tableData.relations;
this.options = options;
this.space = makeIndent(this.options.spaces, this.options.indentation);
}
write() {
if (this.options.noWrite) {
return Promise.resolve();
}
mkdirp.sync(path.resolve(this.options.directory || "./models"));
const tables = _.keys(this.tableText);
// write the individual model files
const promises = tables.map(t => {
return this.createFile(t);
});
const isTypeScript = this.options.lang === 'ts';
const assoc = this.createAssociations(isTypeScript);
// get table names without schema
// TODO: add schema to model and file names when schema is non-default for the dialect
const tableNames = tables.map(t => {
const [schemaName, tableName] = qNameSplit(t);
return tableName as string;
}).sort();
// write the init-models file
if (!this.options.noInitModels) {
const initString = this.createInitString(tableNames, assoc, this.options.lang);
const initFilePath = path.join(this.options.directory, "init-models" + (isTypeScript ? '.ts' : '.js'));
const writeFile = util.promisify(fs.writeFile);
const initPromise = writeFile(path.resolve(initFilePath), initString);
promises.push(initPromise);
}
return Promise.all(promises);
}
private createInitString(tableNames: string[], assoc: string, lang?: string) {
switch (lang) {
case 'ts':
return this.createTsInitString(tableNames, assoc);
case 'esm':
return this.createESMInitString(tableNames, assoc);
case 'es6':
return this.createES5InitString(tableNames, assoc, "const");
default:
return this.createES5InitString(tableNames, assoc, "var");
}
}
private createFile(table: string) {
// FIXME: schema is not used to write the file name and there could be collisions. For now it
// is up to the developer to pick the right schema, and potentially chose different output
// folders for each different schema.
const [schemaName, tableName] = qNameSplit(table);
const fileName = this.options.caseModelPrefix + recase(this.options.caseFile, tableName, this.options.singularize) + this.options.caseModelSuffix;
const filePath = path.join(this.options.directory, fileName + (this.options.lang === 'ts' ? '.ts' : '.js'));
const writeFile = util.promisify(fs.writeFile);
return writeFile(path.resolve(filePath), this.tableText[table]);
}
/** Create the belongsToMany/belongsTo/hasMany/hasOne association strings */
private createAssociations(typeScript: boolean) {
let strBelongs = "";
let strBelongsToMany = "";
const sp = this.space[1];
const rels = this.relations;
rels.forEach(rel => {
if (rel.isM2M) {
const asprop = recase(this.options.caseProp, pluralize(rel.childProp));
strBelongsToMany += `${sp}${rel.parentModel}.belongsToMany(${rel.childModel}, { as: '${asprop}', through: ${rel.joinModel}, foreignKey: "${rel.parentId}", otherKey: "${rel.childId}" });\n`;
} else {
// const bAlias = (this.options.noAlias && rel.parentModel.toLowerCase() === rel.parentProp.toLowerCase()) ? '' : `as: "${rel.parentProp}", `;
const asParentProp = recase(this.options.caseProp, rel.parentProp);
const bAlias = this.options.noAlias ? '' : `as: "${asParentProp}", `;
strBelongs += `${sp}${rel.childModel}.belongsTo(${rel.parentModel}, { ${bAlias}foreignKey: "${rel.parentId}"});\n`;
const hasRel = rel.isOne ? "hasOne" : "hasMany";
// const hAlias = (this.options.noAlias && Utils.pluralize(rel.childModel.toLowerCase()) === rel.childProp.toLowerCase()) ? '' : `as: "${rel.childProp}", `;
const asChildProp = recase(this.options.caseProp, rel.childProp);
const hAlias = this.options.noAlias ? '' : `as: "${asChildProp}", `;
strBelongs += `${sp}${rel.parentModel}.${hasRel}(${rel.childModel}, { ${hAlias}foreignKey: "${rel.parentId}"});\n`;
}
});
// belongsToMany must come first
return strBelongsToMany + strBelongs;
}
// create the TypeScript init-models file to load all the models into Sequelize
private createTsInitString(tables: string[], assoc: string) {
let str = 'import type { Sequelize } from "sequelize";\n';
const sp = this.space[1];
const modelNames: string[] = [];
// import statements
tables.forEach(t => {
const fileName = this.options.caseModelPrefix + recase(this.options.caseFile, t, this.options.singularize) + this.options.caseModelSuffix;
const modelName = makeTableName(this.options.caseModel,this.options.caseModelPrefix,this.options.caseModelSuffix, t, this.options.singularize, this.options.lang);
modelNames.push(modelName);
str += `import { ${modelName} as _${modelName} } from "./${fileName}";\n`;
str += `import type { ${modelName}Attributes, ${modelName}CreationAttributes } from "./${fileName}";\n`;
});
// re-export the model classes
str += '\nexport {\n';
modelNames.forEach(m => {
str += `${sp}_${m} as ${m},\n`;
});
str += '};\n';
// re-export the model attirbutes
str += '\nexport type {\n';
modelNames.forEach(m => {
str += `${sp}${m}Attributes,\n`;
str += `${sp}${m}CreationAttributes,\n`;
});
str += '};\n\n';
// create the initialization function
str += 'export function initModels(sequelize: Sequelize) {\n';
modelNames.forEach(m => {
str += `${sp}const ${m} = _${m}.initModel(sequelize);\n`;
});
// add the asociations
str += "\n" + assoc;
// return the models
str += `\n${sp}return {\n`;
modelNames.forEach(m => {
str += `${this.space[2]}${m}: ${m},\n`;
});
str += `${sp}};\n`;
str += '}\n';
return str;
}
// create the ES5 init-models file to load all the models into Sequelize
private createES5InitString(tables: string[], assoc: string, vardef: string) {
let str = `${vardef} DataTypes = require("sequelize").DataTypes;\n`;
const sp = this.space[1];
const modelNames: string[] = [];
// import statements
tables.forEach(t => {
const fileName = this.options.caseModelPrefix + recase(this.options.caseFile, t, this.options.singularize) + this.options.caseModelSuffix;
const modelName = makeTableName(this.options.caseModel,this.options.caseModelPrefix,this.options.caseModelSuffix, t, this.options.singularize, this.options.lang);
modelNames.push(modelName);
str += `${vardef} _${modelName} = require("./${fileName}");\n`;
});
// create the initialization function
str += '\nfunction initModels(sequelize) {\n';
modelNames.forEach(m => {
str += `${sp}${vardef} ${m} = _${m}(sequelize, DataTypes);\n`;
});
// add the asociations
str += "\n" + assoc;
// return the models
str += `\n${sp}return {\n`;
modelNames.forEach(m => {
str += `${this.space[2]}${m},\n`;
});
str += `${sp}};\n`;
str += '}\n';
str += 'module.exports = initModels;\n';
str += 'module.exports.initModels = initModels;\n';
str += 'module.exports.default = initModels;\n';
return str;
}
// create the ESM init-models file to load all the models into Sequelize
private createESMInitString(tables: string[], assoc: string) {
let str = 'import _sequelize from "sequelize";\n';
str += 'const DataTypes = _sequelize.DataTypes;\n';
const sp = this.space[1];
const modelNames: string[] = [];
// import statements
tables.forEach(t => {
const fileName = recase(this.options.caseFile, t, this.options.singularize);
const modelName = makeTableName(this.options.caseModel, this.options.caseModelPrefix,this.options.caseModelSuffix, t, this.options.singularize, this.options.lang);
modelNames.push(modelName);
str += `import _${modelName} from "./${fileName}.js";\n`;
});
// create the initialization function
str += '\nexport default function initModels(sequelize) {\n';
modelNames.forEach(m => {
str += `${sp}const ${m} = _${m}.init(sequelize, DataTypes);\n`;
});
// add the associations
str += "\n" + assoc;
// return the models
str += `\n${sp}return {\n`;
modelNames.forEach(m => {
str += `${this.space[2]}${m},\n`;
});
str += `${sp}};\n`;
str += '}\n';
return str;
}
}