-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathTypeORMConverter.ts
549 lines (474 loc) · 16.5 KB
/
TypeORMConverter.ts
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
import { Container } from 'typedi';
import { getMetadataArgsStorage } from 'typeorm';
import { ColumnMetadata, getMetadataStorage, ModelMetadata } from '../metadata';
import { WhereOperator } from '../torm';
import {
columnToGraphQLDataType,
columnToGraphQLType,
columnToTypeScriptType
} from './type-conversion';
const ignoreBaseModels = ['BaseModel', 'BaseModelUUID'];
export function getColumnsForModel(model: ModelMetadata) {
const models = [model];
const columns: { [key: string]: ColumnMetadata } = {};
let superProto = model.klass ? model.klass.__proto__ : null;
while (superProto) {
const superModel = getMetadataStorage().getModel(superProto.name);
superModel && models.unshift(superModel);
superProto = superProto.__proto__;
}
models.forEach(aModel => {
aModel.columns.forEach((col: ColumnMetadata) => {
columns[col.propertyName] = col;
});
});
return Object.values(columns);
}
export function filenameToImportPath(filename: string): string {
return filename.replace(/\.(j|t)s$/, '').replace(/\\/g, '/');
}
export function generateEnumMapImports(): string[] {
const imports: string[] = [];
const enumMap = getMetadataStorage().enumMap;
// Keep track of already imported items so that we don't attempt to import twice in the event the
// enum is used in multiple models
const imported = new Set();
Object.keys(enumMap).forEach((tableName: string) => {
Object.keys(enumMap[tableName]).forEach((columnName: string) => {
const enumColumn = enumMap[tableName][columnName];
if (imported.has(enumColumn.name)) {
return;
}
imported.add(enumColumn.name);
const filename = filenameToImportPath(enumColumn.filename);
imports.push(`import { ${enumColumn.name} } from '${filename}'
`);
});
});
return imports;
}
export function generateClassImports(): string[] {
const imports: string[] = [];
const classMap = getMetadataStorage().classMap;
Object.keys(classMap).forEach((tableName: string) => {
const classObj = classMap[tableName];
const filename = filenameToImportPath(classObj.filename);
// Need to ts-ignore here for when we export compiled code
// otherwise, it says we can't find a declaration file for this from the compiled code
imports.push('// @ts-ignore\n');
imports.push(`import { ${classObj.name} } from '${filename}'
`);
});
return imports;
}
export function entityToWhereUniqueInput(model: ModelMetadata): string {
const uniques = getMetadataStorage().uniquesForModel(model);
const others = getMetadataArgsStorage().uniques;
const modelUniques: { [key: string]: string } = {};
others.forEach(o => {
const name = (o.target as Function).name;
const columns = o.columns as string[];
if (name === model.name && columns) {
columns.forEach((col: string) => {
modelUniques[col] = col;
});
}
});
uniques.forEach(unique => {
modelUniques[unique] = unique;
});
const distinctUniques = Object.keys(modelUniques);
// If there is only one unique field, it should not be nullable
const uniqueFieldsAreNullable = distinctUniques.length > 1;
let fieldsTemplate = '';
const modelColumns = getColumnsForModel(model);
modelColumns.forEach((column: ColumnMetadata) => {
// Uniques can be from Field or Unique annotations
if (!modelUniques[column.propertyName]) {
return;
}
const nullable = uniqueFieldsAreNullable ? ', { nullable: true }' : '';
let graphQLDataType = columnToGraphQLDataType(column);
let tsType = columnToTypeScriptType(column);
if (column.array) {
tsType = tsType.concat('[]');
graphQLDataType = `[${graphQLDataType}]`;
}
fieldsTemplate += `
@TypeGraphQLField(() => ${graphQLDataType}${nullable})
${column.propertyName}?: ${tsType};
`;
});
const superName = model.klass ? model.klass.__proto__.name : null;
const classDeclaration =
superName && !ignoreBaseModels.includes(superName)
? `${model.name}WhereUniqueInput extends ${superName}WhereUniqueInput`
: `${model.name}WhereUniqueInput`;
const template = `
@TypeGraphQLInputType()
export class ${classDeclaration} {
${fieldsTemplate}
}
`;
return template;
}
export function entityToCreateInput(model: ModelMetadata): string {
const idsOnCreate =
(Container.get('Config') as any).get('ALLOW_OPTIONAL_ID_ON_CREATE') === 'true';
let fieldTemplates = '';
if (idsOnCreate) {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
id?: string;
`;
}
const modelColumns = getColumnsForModel(model);
modelColumns.forEach((column: ColumnMetadata) => {
if (!column.editable || column.readonly) {
return;
}
let graphQLDataType = columnToGraphQLDataType(column);
const nullable = column.nullable ? '{ nullable: true }' : '';
const tsRequired = column.nullable ? '?' : '!';
let tsType = columnToTypeScriptType(column);
if (column.array) {
tsType = tsType.concat('[]');
graphQLDataType = `[${graphQLDataType}]`;
}
if (columnRequiresExplicitGQLType(column)) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, ${nullable})
${column.propertyName}${tsRequired}: ${tsType};
`;
} else {
fieldTemplates += `
@TypeGraphQLField(${nullable})
${column.propertyName}${tsRequired}: ${tsType};
`;
}
});
const superName = model.klass ? model.klass.__proto__.name : null;
const classDeclaration =
superName && !ignoreBaseModels.includes(superName)
? `${model.name}CreateInput extends ${superName}CreateInput`
: `${model.name}CreateInput`;
return `
@TypeGraphQLInputType()
export class ${classDeclaration} {
${fieldTemplates}
}
`;
}
export function entityToUpdateInput(model: ModelMetadata): string {
let fieldTemplates = '';
const modelColumns = getColumnsForModel(model);
modelColumns.forEach((column: ColumnMetadata) => {
if (!column.editable || column.readonly) {
return;
}
// TODO: also don't allow updated foreign key fields
// Example: photo.userId: String
let graphQLDataType = columnToGraphQLDataType(column);
let tsType = columnToTypeScriptType(column);
if (column.array) {
tsType = tsType.concat('[]');
graphQLDataType = `[${graphQLDataType}]`;
}
if (columnRequiresExplicitGQLType(column)) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}?: ${tsType};
`;
} else {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
${column.propertyName}?: ${tsType};
`;
}
});
const superName = model.klass ? model.klass.__proto__.name : null;
const classDeclaration =
superName && !ignoreBaseModels.includes(superName)
? `${model.name}UpdateInput extends ${superName}UpdateInput`
: `${model.name}UpdateInput`;
return `
@TypeGraphQLInputType()
export class ${classDeclaration} {
${fieldTemplates}
}
`;
}
// Constructs required arguments needed when doing an update
export function entityToUpdateInputArgs(model: ModelMetadata): string {
return `
@ArgsType()
export class ${model.name}UpdateArgs {
@TypeGraphQLField() data!: ${model.name}UpdateInput;
@TypeGraphQLField() where!: ${model.name}WhereUniqueInput;
}
`;
}
function columnToTypes(column: ColumnMetadata) {
const graphqlType = columnToGraphQLType(column);
const tsType = columnToTypeScriptType(column);
return { graphqlType, tsType };
}
export function entityToWhereInput(model: ModelMetadata): string {
let fieldTemplates = '';
const modelColumns = getColumnsForModel(model);
modelColumns.forEach((column: ColumnMetadata) => {
// If user specifically says not to filter (filter: false), then don't provide where inputs
// Also, if the columns is "write only", then it cannot therefore be read and shouldn't have filters
if (!column.filter || column.writeonly) {
return;
}
function allowFilter(op: WhereOperator) {
if (column.filter === true) {
return true;
}
if (column.filter === false) {
return false;
}
return !!column.filter?.includes(op);
}
const { tsType } = columnToTypes(column);
const graphQLDataType = columnToGraphQLDataType(column);
// TODO: for foreign key fields, only allow the same filters as ID below
// Example: photo.userId: String
if (column.array) {
fieldTemplates += `
@TypeGraphQLField(() => [${graphQLDataType}],{ nullable: true })
${column.propertyName}_containsAll?: [${tsType}];
@TypeGraphQLField(() => [${graphQLDataType}],{ nullable: true })
${column.propertyName}_containsNone?: [${tsType}];
@TypeGraphQLField(() => [${graphQLDataType}],{ nullable: true })
${column.propertyName}_containsAny?: [${tsType}];
`;
} else if (column.type === 'id') {
const graphQlType = 'ID';
if (allowFilter('eq')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQlType},{ nullable: true })
${column.propertyName}_eq?: string;
`;
}
if (allowFilter('in')) {
fieldTemplates += `
@TypeGraphQLField(() => [${graphQlType}], { nullable: true })
${column.propertyName}_in?: string[];
`;
}
} else if (column.type === 'boolean') {
if (allowFilter('eq')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType},{ nullable: true })
${column.propertyName}_eq?: Boolean;
`;
}
// V3: kill the boolean "in" clause
if (allowFilter('in')) {
fieldTemplates += `
@TypeGraphQLField(() => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: Boolean[];
`;
}
} else if (column.type === 'string' || column.type === 'email') {
// TODO: do we need NOT?
// `${column.propertyName}_not`
if (allowFilter('eq')) {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
${column.propertyName}_eq?: ${tsType};
`;
}
if (allowFilter('contains')) {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
${column.propertyName}_contains?: ${tsType};
`;
}
if (allowFilter('startsWith')) {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
${column.propertyName}_startsWith?: ${tsType};
`;
}
if (allowFilter('endsWith')) {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
${column.propertyName}_endsWith?: ${tsType};
`;
}
if (allowFilter('in')) {
fieldTemplates += `
@TypeGraphQLField(() => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: ${tsType}[];
`;
}
} else if (column.type === 'float' || column.type === 'integer' || column.type === 'numeric') {
if (allowFilter('eq')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_eq?: ${tsType};
`;
}
if (allowFilter('gt')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_gt?: ${tsType};
`;
}
if (allowFilter('gte')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_gte?: ${tsType};
`;
}
if (allowFilter('lt')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_lt?: ${tsType};
`;
}
if (allowFilter('lte')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_lte?: ${tsType};
`;
}
if (allowFilter('in')) {
fieldTemplates += `
@TypeGraphQLField(() => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: ${tsType}[];
`;
}
} else if (column.type === 'date' || column.type === 'datetime' || column.type === 'dateonly') {
// I really don't like putting this magic here, but it has to go somewhere
// This deletedAt_all turns off the default filtering of soft-deleted items
if (column.propertyName === 'deletedAt') {
fieldTemplates += `
@TypeGraphQLField({ nullable: true })
deletedAt_all?: Boolean;
`;
}
if (allowFilter('eq')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_eq?: ${tsType};
`;
}
if (allowFilter('lt')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_lt?: ${tsType};
`;
}
if (allowFilter('lte')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_lte?: ${tsType};
`;
}
if (allowFilter('gt')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_gt?: ${tsType};
`;
}
if (allowFilter('gte')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_gte?: ${tsType};
`;
}
} else if (column.type === 'enum') {
if (allowFilter('eq')) {
fieldTemplates += `
@TypeGraphQLField(() => ${graphQLDataType}, { nullable: true })
${column.propertyName}_eq?: ${graphQLDataType};
`;
}
if (allowFilter('in')) {
fieldTemplates += `
@TypeGraphQLField(() => [${graphQLDataType}], { nullable: true })
${column.propertyName}_in?: ${graphQLDataType}[];
`;
}
} else if (column.type === 'json') {
fieldTemplates += `
@TypeGraphQLField(() => GraphQLJSONObject, { nullable: true })
${column.propertyName}_json?: JsonObject;
`;
}
});
const superName = model.klass ? model.klass.__proto__.name : null;
const classDeclaration =
superName && !ignoreBaseModels.includes(superName)
? `${model.name}WhereInput extends ${superName}WhereInput`
: `${model.name}WhereInput`;
return `
@TypeGraphQLInputType()
export class ${classDeclaration} {
${fieldTemplates}
}
`;
}
export function entityToWhereArgs(model: ModelMetadata): string {
return `
@ArgsType()
export class ${model.name}WhereArgs extends PaginationArgs {
@TypeGraphQLField(() => ${model.name}WhereInput, { nullable: true })
where?: ${model.name}WhereInput;
@TypeGraphQLField(() => ${model.name}OrderByEnum, { nullable: true })
orderBy?: ${model.name}OrderByEnum;
}
`;
}
// Note: it would be great to inject a single `Arg` with the [model.nameCreateInput] array arg,
// but that is not allowed by TypeGraphQL
export function entityToCreateManyArgs(model: ModelMetadata): string {
return `
@ArgsType()
export class ${model.name}CreateManyArgs {
@TypeGraphQLField(() => [${model.name}CreateInput])
data!: ${model.name}CreateInput[];
}
`;
}
export function entityToOrderByEnum(model: ModelMetadata): string {
let fieldsTemplate = '';
const modelColumns = getColumnsForModel(model);
modelColumns.forEach((column: ColumnMetadata) => {
if (column.type === 'json') {
return;
}
// If user says this is not sortable, then don't allow sorting
// Also, if the column is "write only", therefore it cannot be read and shouldn't be sortable
// Also, doesn't make sense to sort arrays
if (column.sort && !column.writeonly && !column.array) {
fieldsTemplate += `
${column.propertyName}_ASC = '${column.propertyName}_ASC',
${column.propertyName}_DESC = '${column.propertyName}_DESC',
`;
}
});
return `
export enum ${model.name}OrderByEnum {
${fieldsTemplate}
}
registerEnumType(${model.name}OrderByEnum, {
name: '${model.name}OrderByInput'
});
`;
}
function columnRequiresExplicitGQLType(column: ColumnMetadata) {
return (
column.enum ||
column.array ||
column.type === 'json' ||
column.type === 'id' ||
column.type === 'date' ||
column.type === 'datetime' ||
column.type === 'dateonly'
);
}