@dextinity/api-generator 2.0.0-canary-20260729062014

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +24 -0
  2. package/bin/api-generator.js +6 -0
  3. package/lib/apiGenerator.d.ts +1 -0
  4. package/lib/apiGenerator.js +7 -0
  5. package/lib/commands/generate/generate-command.d.ts +2 -0
  6. package/lib/commands/generate/generate-command.js +19 -0
  7. package/lib/commands/generate/generateCrud/build-options.d.ts +24 -0
  8. package/lib/commands/generate/generateCrud/build-options.js +144 -0
  9. package/lib/commands/generate/generateCrud/generate-crud.d.ts +18 -0
  10. package/lib/commands/generate/generateCrud/generate-crud.js +1092 -0
  11. package/lib/commands/generate/generateCrud/generate-enum-filter-dto.d.ts +2 -0
  12. package/lib/commands/generate/generateCrud/generate-enum-filter-dto.js +76 -0
  13. package/lib/commands/generate/generateCrud/generate-payload-object-types.d.ts +12 -0
  14. package/lib/commands/generate/generateCrud/generate-payload-object-types.js +38 -0
  15. package/lib/commands/generate/generateCrud/generate-service-hook-call.d.ts +8 -0
  16. package/lib/commands/generate/generateCrud/generate-service-hook-call.js +47 -0
  17. package/lib/commands/generate/generateCrudInput/generate-crud-input.d.ts +12 -0
  18. package/lib/commands/generate/generateCrudInput/generate-crud-input.js +499 -0
  19. package/lib/commands/generate/generateCrudSingle/generate-crud-single.d.ts +4 -0
  20. package/lib/commands/generate/generateCrudSingle/generate-crud-single.js +134 -0
  21. package/lib/commands/generate/generateFiles.d.ts +13 -0
  22. package/lib/commands/generate/generateFiles.js +81 -0
  23. package/lib/commands/generate/utils/build-name-variants.d.ts +9 -0
  24. package/lib/commands/generate/utils/build-name-variants.js +24 -0
  25. package/lib/commands/generate/utils/constants.d.ts +2 -0
  26. package/lib/commands/generate/utils/constants.js +5 -0
  27. package/lib/commands/generate/utils/find-hooks-service.d.ts +19 -0
  28. package/lib/commands/generate/utils/find-hooks-service.js +185 -0
  29. package/lib/commands/generate/utils/generate-imports-code.d.ts +5 -0
  30. package/lib/commands/generate/utils/generate-imports-code.js +32 -0
  31. package/lib/commands/generate/utils/ts-morph-helper.d.ts +18 -0
  32. package/lib/commands/generate/utils/ts-morph-helper.js +237 -0
  33. package/lib/commands/generate/utils/write-generated-file.d.ts +3 -0
  34. package/lib/commands/generate/utils/write-generated-file.js +113 -0
  35. package/lib/commands/generate/utils/write-generated-files.d.ts +7 -0
  36. package/lib/commands/generate/utils/write-generated-files.js +9 -0
  37. package/lib/commands/generate/watchMode/handleChildProcess.d.ts +2 -0
  38. package/lib/commands/generate/watchMode/handleChildProcess.js +26 -0
  39. package/lib/commands/generate/watchMode/watchMode.d.ts +6 -0
  40. package/lib/commands/generate/watchMode/watchMode.js +70 -0
  41. package/package.json +79 -0
@@ -0,0 +1,499 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateCrudInput = generateCrudInput;
4
+ const cms_api_1 = require("@dextinity/cms-api");
5
+ const class_validator_1 = require("class-validator");
6
+ const ts_morph_1 = require("ts-morph");
7
+ const build_options_1 = require("../generateCrud/build-options");
8
+ const build_name_variants_1 = require("../utils/build-name-variants");
9
+ const constants_1 = require("../utils/constants");
10
+ const generate_imports_code_1 = require("../utils/generate-imports-code");
11
+ const ts_morph_helper_1 = require("../utils/ts-morph-helper");
12
+ function tsCodeRecordToString(object) {
13
+ const filteredEntries = Object.entries(object).filter(([key, value]) => value !== undefined);
14
+ if (filteredEntries.length == 0) {
15
+ return "";
16
+ }
17
+ return `{${filteredEntries.map(([key, value]) => `${key}: ${value},`).join("\n")}}`;
18
+ }
19
+ function findReferenceTargetType(targetMeta, referencedColumnName) {
20
+ const referencedColumnProp = targetMeta?.props.find((p) => p.name == referencedColumnName);
21
+ if (!referencedColumnProp) {
22
+ throw new Error("referencedColumnProp not found");
23
+ }
24
+ if (referencedColumnProp.type == "uuid") {
25
+ return "uuid";
26
+ }
27
+ else if (referencedColumnProp.type == "text") {
28
+ return "string";
29
+ }
30
+ else if (referencedColumnProp.type == "string") {
31
+ return "string";
32
+ }
33
+ else if (referencedColumnProp.type == "integer" || referencedColumnProp.type == "int") {
34
+ return "integer";
35
+ }
36
+ else {
37
+ return null;
38
+ }
39
+ }
40
+ async function generateCrudInput(generatorOptions,
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ metadata, options = {
43
+ nested: false,
44
+ excludeFields: [],
45
+ generateUpdateInput: true,
46
+ }) {
47
+ const generatedFiles = [];
48
+ const { dedicatedResolverArgProps, targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
49
+ const props = metadata.props
50
+ .filter((prop) => {
51
+ return !prop.embedded;
52
+ })
53
+ .filter((prop) => {
54
+ return (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "input");
55
+ })
56
+ .filter((prop) => {
57
+ //filter out props that are dedicatedResolverArgProps
58
+ return !dedicatedResolverArgProps.some((dedicatedResolverArgProp) => dedicatedResolverArgProp.name === prop.name);
59
+ })
60
+ .filter((prop) => !options.excludeFields.includes(prop.name));
61
+ let fieldsOut = "";
62
+ const imports = [
63
+ { name: "IsSlug", importPath: "@dextinity/cms-api" },
64
+ { name: "RootBlockInputScalar", importPath: "@dextinity/cms-api" },
65
+ { name: "IsNullable", importPath: "@dextinity/cms-api" },
66
+ { name: "PartialType", importPath: "@dextinity/cms-api" },
67
+ { name: "BlockInputInterface", importPath: "@dextinity/cms-api" },
68
+ { name: "isBlockInputInterface", importPath: "@dextinity/cms-api" },
69
+ { name: "IsString", importPath: "class-validator" },
70
+ { name: "IsNotEmpty", importPath: "class-validator" },
71
+ { name: "ValidateNested", importPath: "class-validator" },
72
+ { name: "IsNumber", importPath: "class-validator" },
73
+ { name: "IsBoolean", importPath: "class-validator" },
74
+ { name: "IsDate", importPath: "class-validator" },
75
+ { name: "IsDateString", importPath: "class-validator" },
76
+ { name: "IsOptional", importPath: "class-validator" },
77
+ { name: "IsEnum", importPath: "class-validator" },
78
+ { name: "IsUUID", importPath: "class-validator" },
79
+ { name: "IsArray", importPath: "class-validator" },
80
+ { name: "IsInt", importPath: "class-validator" },
81
+ ];
82
+ for (const prop of props) {
83
+ let type = prop.type;
84
+ const fieldName = prop.name;
85
+ const definedDecorators = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getDecorators();
86
+ const decorators = [];
87
+ let isOptional = prop.nullable;
88
+ if (prop.name != "position") {
89
+ if (!prop.nullable) {
90
+ decorators.push("@IsNotEmpty()");
91
+ }
92
+ else {
93
+ decorators.push("@IsNullable()");
94
+ }
95
+ }
96
+ if (["id", "createdAt", "updatedAt", "scope"].includes(prop.name)) {
97
+ //skip those (TODO find a non-magic solution?)
98
+ continue;
99
+ }
100
+ else if (prop.name == "position") {
101
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
102
+ const defaultValue = initializer == "undefined" || initializer == "null" ? "null" : initializer;
103
+ const fieldOptions = tsCodeRecordToString({ nullable: "true", defaultValue });
104
+ isOptional = true;
105
+ decorators.push(`@IsOptional()`);
106
+ imports.push({ name: "Min", importPath: "class-validator" });
107
+ decorators.push(`@Min(1)`);
108
+ decorators.push("@IsInt()");
109
+ decorators.push(`@Field(() => Int, ${fieldOptions})`);
110
+ type = "number";
111
+ }
112
+ else if (prop.enum) {
113
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
114
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined) ? "null" : initializer;
115
+ const fieldOptions = tsCodeRecordToString({ nullable: prop.nullable ? "true" : undefined, defaultValue });
116
+ const enumName = (0, ts_morph_helper_1.findEnumName)(prop.name, metadata);
117
+ const importPath = (0, ts_morph_helper_1.findEnumImportPath)(enumName, `${targetDirectory}/dto`, metadata);
118
+ imports.push({ name: enumName, importPath });
119
+ decorators.push(`@IsEnum(${enumName})`);
120
+ decorators.push(`@Field(() => ${enumName}, ${fieldOptions})`);
121
+ type = enumName;
122
+ }
123
+ else if (prop.type === "EnumArrayType") {
124
+ if (prop.nullable) {
125
+ console.warn(`${prop.name}: Nullable enum arrays are not supported`);
126
+ }
127
+ decorators.length = 0; //remove @IsNotEmpty
128
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
129
+ const fieldOptions = tsCodeRecordToString({ defaultValue: initializer });
130
+ const enumName = (0, ts_morph_helper_1.findEnumName)(prop.name, metadata);
131
+ const importPath = (0, ts_morph_helper_1.findEnumImportPath)(enumName, `${targetDirectory}/dto`, metadata);
132
+ imports.push({ name: enumName, importPath });
133
+ decorators.push(`@IsEnum(${enumName}, { each: true })`);
134
+ decorators.push(`@Field(() => [${enumName}], ${fieldOptions})`);
135
+ type = `${enumName}[]`;
136
+ }
137
+ else if (prop.type === "string" || prop.type === "text") {
138
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
139
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined) ? "null" : initializer;
140
+ const fieldOptions = tsCodeRecordToString({ nullable: prop.nullable ? "true" : undefined, defaultValue });
141
+ decorators.push("@IsString()");
142
+ if (prop.name.startsWith("scope_")) {
143
+ continue;
144
+ }
145
+ else if (prop.name === "slug") {
146
+ //TODO find a non-magic solution
147
+ decorators.push("@IsSlug()");
148
+ }
149
+ decorators.push(`@Field(${fieldOptions})`);
150
+ type = "string";
151
+ }
152
+ else if (constants_1.numberTypes.includes(prop.type)) {
153
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
154
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined) ? "null" : initializer;
155
+ const fieldOptions = tsCodeRecordToString({ nullable: prop.nullable ? "true" : undefined, defaultValue });
156
+ if (constants_1.integerTypes.includes(prop.columnTypes[0])) {
157
+ decorators.push("@IsInt()");
158
+ decorators.push(`@Field(() => Int, ${fieldOptions})`);
159
+ }
160
+ else {
161
+ decorators.push("@IsNumber()");
162
+ decorators.push(`@Field(${fieldOptions})`);
163
+ }
164
+ type = "number";
165
+ }
166
+ else if (prop.type === "DateType") {
167
+ // ISO Date without time
168
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
169
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined) ? "null" : initializer;
170
+ const fieldOptions = tsCodeRecordToString({ nullable: prop.nullable ? "true" : undefined, defaultValue });
171
+ decorators.push("@IsDateString()");
172
+ decorators.push(`@Field(() => GraphQLLocalDate, ${fieldOptions})`);
173
+ type = "string";
174
+ }
175
+ else if (prop.type === "Date") {
176
+ // DateTime
177
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
178
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined) ? "null" : initializer;
179
+ const fieldOptions = tsCodeRecordToString({ nullable: prop.nullable ? "true" : undefined, defaultValue });
180
+ decorators.push("@IsDate()");
181
+ decorators.push(`@Field(${fieldOptions})`);
182
+ type = "Date";
183
+ }
184
+ else if (prop.type === "BooleanType" || prop.type === "boolean") {
185
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
186
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined) ? "null" : initializer;
187
+ const fieldOptions = tsCodeRecordToString({ nullable: prop.nullable ? "true" : undefined, defaultValue });
188
+ decorators.push("@IsBoolean()");
189
+ decorators.push(`@Field(${fieldOptions})`);
190
+ type = "boolean";
191
+ }
192
+ else if (prop.type === "RootBlockType") {
193
+ const blockName = (0, ts_morph_helper_1.findBlockName)(prop.name, metadata);
194
+ const importPath = (0, ts_morph_helper_1.findBlockImportPath)(blockName, `${targetDirectory}/dto`, metadata);
195
+ imports.push({ name: blockName, importPath });
196
+ decorators.push(`@Field(() => RootBlockInputScalar(${blockName})${prop.nullable ? ", { nullable: true }" : ""})`);
197
+ decorators.push(`@Transform(({ value }) => (isBlockInputInterface(value) ? value : ${blockName}.blockInputFactory(value)), { toClassOnly: true })`);
198
+ decorators.push("@ValidateNested()");
199
+ type = "BlockInputInterface";
200
+ }
201
+ else if (prop.kind == "m:1") {
202
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
203
+ const defaultValueNull = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined);
204
+ const fieldOptions = tsCodeRecordToString({
205
+ nullable: prop.nullable ? "true" : undefined,
206
+ defaultValue: defaultValueNull ? "null" : undefined,
207
+ });
208
+ decorators.push(`@Field(() => ID, ${fieldOptions})`);
209
+ if (prop.referencedColumnNames.length > 1) {
210
+ console.warn(`${prop.name}: Composite keys are not supported`);
211
+ continue;
212
+ }
213
+ const refType = findReferenceTargetType(prop.targetMeta, prop.referencedColumnNames[0]);
214
+ if (refType == "uuid") {
215
+ type = "string";
216
+ decorators.push("@IsUUID()");
217
+ }
218
+ else if (refType == "string") {
219
+ type = "string";
220
+ decorators.push("@IsString()");
221
+ }
222
+ else if (refType == "integer") {
223
+ type = "number";
224
+ decorators.push("@Transform(({ value }) => (value ? parseInt(value) : null))");
225
+ decorators.push("@IsInt()");
226
+ }
227
+ else {
228
+ console.warn(`${prop.name}: Unsupported referenced type`);
229
+ continue;
230
+ }
231
+ }
232
+ else if (prop.kind == "1:m") {
233
+ if (prop.orphanRemoval) {
234
+ //if orphanRemoval is enabled, we need to generate a nested input type
235
+ decorators.length = 0;
236
+ if (!prop.targetMeta) {
237
+ throw new Error("No targetMeta");
238
+ }
239
+ const inputNameClassName = `${metadata.className}Nested${prop.targetMeta.className}Input`;
240
+ {
241
+ const excludeFields = prop.targetMeta.props.filter((p) => p.kind == "m:1" && p.targetMeta == metadata).map((p) => p.name);
242
+ const { fileNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
243
+ const { fileNameSingular: targetFileNameSingular } = (0, build_name_variants_1.buildNameVariants)(prop.targetMeta);
244
+ const fileName = `dto/${fileNameSingular}-nested-${targetFileNameSingular}.input.ts`;
245
+ const nestedInputFiles = await generateCrudInput(generatorOptions, prop.targetMeta, {
246
+ nested: true,
247
+ fileName,
248
+ className: inputNameClassName,
249
+ excludeFields,
250
+ });
251
+ generatedFiles.push(...nestedInputFiles);
252
+ imports.push({
253
+ name: inputNameClassName,
254
+ importPath: nestedInputFiles[nestedInputFiles.length - 1].name.replace(/^dto/, ".").replace(/\.ts$/, ""),
255
+ });
256
+ }
257
+ decorators.push(`@Field(() => [${inputNameClassName}], {${prop.nullable ? "nullable: true" : "defaultValue: []"}})`);
258
+ decorators.push(`@IsArray()`);
259
+ decorators.push(`@Type(() => ${inputNameClassName})`);
260
+ type = `${inputNameClassName}[]`;
261
+ }
262
+ else {
263
+ //if orphanRemoval is disabled, we reference the id in input
264
+ decorators.length = 0;
265
+ decorators.push(`@Field(() => [ID], {${prop.nullable ? "nullable: true" : "defaultValue: []"}})`);
266
+ decorators.push(`@IsArray()`);
267
+ if (prop.referencedColumnNames.length > 1) {
268
+ console.warn(`${prop.name}: Composite keys are not supported`);
269
+ continue;
270
+ }
271
+ const refType = findReferenceTargetType(prop.targetMeta, prop.referencedColumnNames[0]);
272
+ if (refType == "uuid") {
273
+ type = "string[]";
274
+ decorators.push("@IsUUID(undefined, { each: true })");
275
+ }
276
+ else if (refType == "string") {
277
+ type = "string[]";
278
+ decorators.push("@IsString({ each: true })");
279
+ }
280
+ else if (refType == "integer") {
281
+ type = "number[]";
282
+ decorators.push("@Transform(({ value }) => value.map((id: string) => parseInt(id)))");
283
+ decorators.push("@IsInt({ each: true })");
284
+ }
285
+ else {
286
+ console.warn(`${prop.name}: Unsupported referenced type`);
287
+ }
288
+ }
289
+ }
290
+ else if (prop.kind == "m:n") {
291
+ decorators.length = 0;
292
+ decorators.push(`@Field(() => [ID], {${prop.nullable ? "nullable: true" : "defaultValue: []"}})`);
293
+ decorators.push(`@IsArray()`);
294
+ if (prop.referencedColumnNames.length > 1) {
295
+ console.warn(`${prop.name}: Composite keys are not supported`);
296
+ continue;
297
+ }
298
+ const refType = findReferenceTargetType(prop.targetMeta, prop.referencedColumnNames[0]);
299
+ if (refType == "uuid") {
300
+ type = "string[]";
301
+ decorators.push("@IsUUID(undefined, { each: true })");
302
+ }
303
+ else if (refType == "string") {
304
+ type = "string[]";
305
+ decorators.push("@IsString({ each: true })");
306
+ }
307
+ else if (refType == "integer") {
308
+ type = "number[]";
309
+ decorators.push("@Transform(({ value }) => value.map((id: string) => parseInt(id)))");
310
+ }
311
+ else {
312
+ console.warn(`${prop.name}: Unsupported referenced type`);
313
+ }
314
+ }
315
+ else if (prop.kind == "1:1") {
316
+ if (!prop.targetMeta) {
317
+ throw new Error("No targetMeta");
318
+ }
319
+ const inputNameClassName = `${metadata.className}Nested${prop.targetMeta.className}Input`;
320
+ {
321
+ const excludeFields = prop.targetMeta.props.filter((p) => p.kind == "1:1" && p.targetMeta == metadata).map((p) => p.name);
322
+ const { fileNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
323
+ const { fileNameSingular: targetFileNameSingular } = (0, build_name_variants_1.buildNameVariants)(prop.targetMeta);
324
+ const fileName = `dto/${fileNameSingular}-nested-${targetFileNameSingular}.input.ts`;
325
+ const nestedInputFiles = await generateCrudInput(generatorOptions, prop.targetMeta, {
326
+ nested: true,
327
+ fileName,
328
+ className: inputNameClassName,
329
+ excludeFields,
330
+ });
331
+ generatedFiles.push(...nestedInputFiles);
332
+ imports.push({
333
+ name: inputNameClassName,
334
+ importPath: nestedInputFiles[nestedInputFiles.length - 1].name.replace(/^dto/, ".").replace(/\.ts$/, ""),
335
+ });
336
+ }
337
+ decorators.push(`@Field(() => ${inputNameClassName}${prop.nullable ? ", { nullable: true }" : ""})`);
338
+ decorators.push(`@Type(() => ${inputNameClassName})`);
339
+ decorators.push("@ValidateNested()");
340
+ type = `${inputNameClassName}`;
341
+ }
342
+ else if (prop.type == "JsonType" || prop.embeddable || prop.type == "ArrayType") {
343
+ const tsProp = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata);
344
+ let tsType = tsProp.getType();
345
+ if (tsType.isUnion() && tsType.getUnionTypes().length == 2 && tsType.getUnionTypes()[0].getText() == "undefined") {
346
+ // undefinded | type (or prop?: type) -> type
347
+ tsType = tsType.getUnionTypes()[1];
348
+ }
349
+ type = tsType.getText(tsProp);
350
+ if (tsType.isArray()) {
351
+ const initializer = tsProp.getInitializer()?.getText();
352
+ const defaultValue = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined)
353
+ ? "null"
354
+ : initializer == "[]"
355
+ ? "[]"
356
+ : undefined;
357
+ const fieldOptions = tsCodeRecordToString({
358
+ nullable: prop.nullable ? "true" : undefined,
359
+ defaultValue: defaultValue,
360
+ });
361
+ decorators.push(`@IsArray()`);
362
+ if (type == "string[]") {
363
+ decorators.push(`@Field(() => [String], ${fieldOptions})`);
364
+ decorators.push("@IsString({ each: true })");
365
+ }
366
+ else if (type == "number[]") {
367
+ decorators.push(`@Field(() => [Number], ${fieldOptions})`);
368
+ decorators.push("@IsNumber({ each: true })");
369
+ }
370
+ else if (type == "boolean[]") {
371
+ decorators.push(`@Field(() => [Boolean], ${fieldOptions})`);
372
+ decorators.push("@IsBoolean({ each: true })");
373
+ }
374
+ else if (tsType.getArrayElementTypeOrThrow().isClass()) {
375
+ const nestedClassName = tsType.getArrayElementTypeOrThrow().getText(tsProp);
376
+ const importPath = (0, ts_morph_helper_1.findInputClassImportPath)(nestedClassName, `${targetDirectory}/dto`, metadata);
377
+ imports.push({ name: nestedClassName, importPath });
378
+ decorators.push(`@ValidateNested()`);
379
+ decorators.push(`@Type(() => ${nestedClassName})`);
380
+ decorators.push(`@Field(() => [${nestedClassName}], ${fieldOptions})`);
381
+ }
382
+ else {
383
+ const typeNode = tsProp.getTypeNodeOrThrow().asKindOrThrow(ts_morph_1.SyntaxKind.ArrayType);
384
+ const elementTypeNode = typeNode.getElementTypeNode();
385
+ if (elementTypeNode.isKind(ts_morph_1.SyntaxKind.TypeReference)) {
386
+ // if the element type is a type reference, we need to find the import path
387
+ const { importPath } = (0, ts_morph_helper_1.findImportPath)(elementTypeNode.getText(), `${targetDirectory}/dto`, metadata);
388
+ if (importPath) {
389
+ imports.push({ name: elementTypeNode.getText(), importPath });
390
+ }
391
+ }
392
+ decorators.push(`@Field(() => [GraphQLJSONObject], ${fieldOptions}) // Warning: this input is not validated properly`);
393
+ }
394
+ }
395
+ else if (tsType.isClass()) {
396
+ const nestedClassName = tsType.getText(tsProp);
397
+ const importPath = (0, ts_morph_helper_1.findInputClassImportPath)(nestedClassName, `${targetDirectory}/dto`, metadata);
398
+ imports.push({ name: nestedClassName, importPath });
399
+ decorators.push(`@ValidateNested()`);
400
+ decorators.push(`@Type(() => ${nestedClassName})`);
401
+ decorators.push(`@Field(() => ${nestedClassName}${prop.nullable ? ", { nullable: true }" : ""})`);
402
+ }
403
+ else {
404
+ const typeNode = tsProp.getTypeNodeOrThrow();
405
+ if (typeNode.isKind(ts_morph_1.SyntaxKind.TypeReference)) {
406
+ // if the element type is a type reference, we need to find the import path
407
+ const { importPath } = (0, ts_morph_helper_1.findImportPath)(typeNode.getText(), `${targetDirectory}/dto`, metadata);
408
+ if (importPath) {
409
+ imports.push({ name: typeNode.getText(), importPath });
410
+ }
411
+ }
412
+ decorators.push(`@Field(() => GraphQLJSONObject${prop.nullable ? ", { nullable: true }" : ""}) // Warning: this input is not validated properly`);
413
+ }
414
+ }
415
+ else if (prop.type == "uuid") {
416
+ const initializer = (0, ts_morph_helper_1.morphTsProperty)(prop.name, metadata).getInitializer()?.getText();
417
+ const defaultValueNull = prop.nullable && (initializer == "undefined" || initializer == "null" || initializer === undefined);
418
+ const fieldOptions = tsCodeRecordToString({
419
+ nullable: prop.nullable ? "true" : undefined,
420
+ defaultValue: defaultValueNull ? "null" : undefined,
421
+ });
422
+ decorators.push(`@Field(() => ID, ${fieldOptions})`);
423
+ decorators.push("@IsUUID()");
424
+ type = "string";
425
+ }
426
+ else if ((0, ts_morph_helper_1.getFieldDecoratorClassName)(prop.name, metadata)) {
427
+ //for custom mikro-orm type
428
+ const className = (0, ts_morph_helper_1.getFieldDecoratorClassName)(prop.name, metadata);
429
+ const importPath = (0, ts_morph_helper_1.findInputClassImportPath)(className, `${targetDirectory}/dto`, metadata);
430
+ imports.push({ name: className, importPath });
431
+ decorators.push(`@ValidateNested()`);
432
+ decorators.push(`@Type(() => ${className})`);
433
+ decorators.push(`@Field(() => ${className}${prop.nullable ? ", { nullable: true }" : ""})`);
434
+ type = className;
435
+ }
436
+ else {
437
+ console.warn(`${prop.name}: unsupported type ${type}`);
438
+ continue;
439
+ }
440
+ const classValidatorValidators = (0, class_validator_1.getMetadataStorage)().getTargetValidationMetadatas(metadata.class, prop.name, false, false, undefined);
441
+ for (const validator of classValidatorValidators) {
442
+ if (validator.propertyName !== prop.name) {
443
+ continue;
444
+ }
445
+ const constraints = (0, class_validator_1.getMetadataStorage)().getTargetValidatorConstraints(validator.constraintCls);
446
+ for (const constraint of constraints) {
447
+ const decorator = definedDecorators.find((decorator) => {
448
+ return (
449
+ // ignore casing since class validator is inconsistent with casing
450
+ decorator.getName().toUpperCase() === constraint.name.toUpperCase() ||
451
+ // some class validator decorators have a prefix "Is" but not in the constraint name
452
+ `Is${decorator.getName()}`.toUpperCase() === constraint.name.toUpperCase());
453
+ });
454
+ if (decorator) {
455
+ const importPath = (0, ts_morph_helper_1.findValidatorImportPath)(decorator.getName(), targetDirectory, metadata);
456
+ if (importPath) {
457
+ imports.push({ name: decorator.getName(), importPath });
458
+ if (!decorators.includes(decorator.getText())) {
459
+ decorators.unshift(decorator.getText());
460
+ }
461
+ }
462
+ }
463
+ else {
464
+ console.warn(`Decorator import for constraint ${constraint.name} not found`);
465
+ }
466
+ }
467
+ }
468
+ fieldsOut += `${decorators.join("\n")}
469
+ ${fieldName}${isOptional ? "?" : ""}: ${type};
470
+
471
+ `;
472
+ }
473
+ const className = options.className ?? `${metadata.className}Input`;
474
+ const inputOut = `import { Field, InputType, ID, Int } from "@nestjs/graphql";
475
+ import { Transform, Type } from "class-transformer";
476
+ import { GraphQLJSONObject, GraphQLLocalDate } from "graphql-scalars";
477
+ ${(0, generate_imports_code_1.generateImportsCode)(imports)}
478
+
479
+ @InputType()
480
+ export class ${className} {
481
+ ${fieldsOut}
482
+ }
483
+
484
+ ${options.generateUpdateInput && !options.nested
485
+ ? `
486
+ @InputType()
487
+ export class ${className.replace(/Input$/, "")}UpdateInput extends PartialType(${className}) {}
488
+ `
489
+ : ""}
490
+ `;
491
+ const { fileNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
492
+ const fileName = options.fileName ?? `dto/${fileNameSingular}.input.ts`;
493
+ generatedFiles.push({
494
+ name: fileName,
495
+ content: inputOut,
496
+ type: "input",
497
+ });
498
+ return generatedFiles;
499
+ }
@@ -0,0 +1,4 @@
1
+ import { type CrudSingleGeneratorOptions } from "@dextinity/cms-api";
2
+ import type { EntityMetadata } from "@mikro-orm/postgresql";
3
+ import type { GeneratedFile } from "../utils/write-generated-files";
4
+ export declare function generateCrudSingle(generatorOptions: CrudSingleGeneratorOptions, metadata: EntityMetadata<any>): Promise<GeneratedFile[]>;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.generateCrudSingle = generateCrudSingle;
37
+ const cms_api_1 = require("@dextinity/cms-api");
38
+ const path = __importStar(require("path"));
39
+ const build_options_1 = require("../generateCrud/build-options");
40
+ const generate_crud_input_1 = require("../generateCrudInput/generate-crud-input");
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ async function generateCrudSingle(generatorOptions, metadata) {
43
+ const classNameSingular = metadata.className;
44
+ const classNamePlural = !metadata.className.endsWith("s") ? `${metadata.className}s` : metadata.className;
45
+ const instanceNameSingular = classNameSingular[0].toLocaleLowerCase() + classNameSingular.slice(1);
46
+ const instanceNamePlural = classNamePlural[0].toLocaleLowerCase() + classNamePlural.slice(1);
47
+ const fileNameSingular = instanceNameSingular.replace(/[A-Z]/g, (i) => `-${i.toLocaleLowerCase()}`);
48
+ const fileNamePlural = instanceNamePlural.replace(/[A-Z]/g, (i) => `-${i.toLocaleLowerCase()}`);
49
+ const { targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
50
+ async function generateCrudResolver() {
51
+ const generatedFiles = [];
52
+ const entityHasRequiredPermission = !!Reflect.getMetadata(cms_api_1.REQUIRED_PERMISSION_METADATA_KEY, metadata.class);
53
+ const scopeProp = metadata.props.find((prop) => prop.name == "scope");
54
+ if (scopeProp && !scopeProp.targetMeta) {
55
+ throw new Error("Scope prop has no targetMeta");
56
+ }
57
+ const blockProps = metadata.props.filter((prop) => {
58
+ return (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "input") && prop.type === "RootBlockType";
59
+ });
60
+ const serviceOut = `import { ObjectQuery } from "@mikro-orm/postgresql";
61
+ import { Injectable } from "@nestjs/common";
62
+ import { ${metadata.className} } from "${path.relative(targetDirectory, metadata.path).replace(/\.ts$/, "")}";
63
+
64
+ @Injectable()
65
+ export class ${classNamePlural}Service {
66
+
67
+ }
68
+ `;
69
+ generatedFiles.push({ name: `${fileNamePlural}.service.ts`, content: serviceOut, type: "service" });
70
+ const resolverOut = `import { FindOptions, EntityManager } from "@mikro-orm/postgresql";
71
+ import { Args, ID, Mutation, Query, Resolver } from "@nestjs/graphql";
72
+ import { ${entityHasRequiredPermission ? "" : "RequiredPermission, "}SortDirection, validateNotModified } from "@dextinity/cms-api";
73
+
74
+ import { ${metadata.className} } from "${path.relative(targetDirectory, metadata.path).replace(/\.ts$/, "")}";
75
+ ${scopeProp && scopeProp.targetMeta
76
+ ? `import { ${scopeProp.targetMeta.className} } from "${path.relative(targetDirectory, scopeProp.targetMeta.path).replace(/\.ts$/, "")}";`
77
+ : ""}
78
+ import { ${classNamePlural}Service } from "./${fileNamePlural}.service";
79
+ import { ${classNameSingular}Input } from "./dto/${fileNameSingular}.input";
80
+
81
+ @Resolver(() => ${metadata.className})
82
+ ${entityHasRequiredPermission ? "" : `@RequiredPermission(${JSON.stringify(generatorOptions.requiredPermission)}${!scopeProp ? `, { skipScopeCheck: true }` : ""})`}
83
+ export class ${classNameSingular}Resolver {
84
+ constructor(
85
+ protected readonly entityManager: EntityManager,
86
+ protected readonly ${instanceNamePlural}Service: ${classNamePlural}Service,
87
+ ) {}
88
+
89
+ @Query(() => ${metadata.className}, { nullable: true })
90
+ async ${instanceNameSingular}(
91
+ ${scopeProp ? `@Args("scope", { type: () => ${scopeProp.type} }) scope: ${scopeProp.type},` : ""}
92
+ ): Promise<${metadata.className} | null> {
93
+ const ${instanceNamePlural} = await this.entityManager.find(${metadata.className}, {${scopeProp ? `scope` : ""}});
94
+ if (${instanceNamePlural}.length > 1) {
95
+ throw new Error("There must be only one ${instanceNameSingular}");
96
+ }
97
+
98
+ return ${instanceNamePlural}.length > 0 ? ${instanceNamePlural}[0] : null;
99
+ }
100
+
101
+ @Mutation(() => ${metadata.className})
102
+ async save${classNameSingular}(
103
+ ${scopeProp ? `@Args("scope", { type: () => ${scopeProp.type} }) scope: ${scopeProp.type},` : ""}
104
+ @Args("input", { type: () => ${classNameSingular}Input }) input: ${classNameSingular}Input
105
+ ): Promise<${metadata.className}> {
106
+ let ${instanceNameSingular} = await this.entityManager.findOne(${metadata.className}, {${scopeProp ? `scope` : ""}});
107
+
108
+ if (!${instanceNameSingular}) {
109
+ ${instanceNameSingular} = this.entityManager.create(${metadata.className}, {
110
+ ...input,
111
+ ${blockProps.length ? `${blockProps.map((prop) => `${prop.name}: input.${prop.name}.transformToBlockData()`).join(", ")}, ` : ""}
112
+ ${scopeProp ? `scope,` : ""}
113
+ });
114
+ }
115
+
116
+ ${instanceNameSingular}.assign({
117
+ ...input,
118
+ ${blockProps.length ? `${blockProps.map((prop) => `${prop.name}: input.${prop.name}.transformToBlockData()`).join(", ")}, ` : ""}
119
+ });
120
+
121
+ await this.entityManager.flush();
122
+
123
+ return ${instanceNameSingular};
124
+ }
125
+ }
126
+ `;
127
+ generatedFiles.push({ name: `${fileNameSingular}.resolver.ts`, content: resolverOut, type: "resolver" });
128
+ return generatedFiles;
129
+ }
130
+ return [
131
+ ...(await (0, generate_crud_input_1.generateCrudInput)(generatorOptions, metadata, { nested: false, excludeFields: [], generateUpdateInput: false })),
132
+ ...(await generateCrudResolver()),
133
+ ];
134
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Generate mode for the generator.
3
+ *
4
+ * Generates CRUD files for all entities or a specific entity available at file path.
5
+ * @param file
6
+ */
7
+ export declare const generateFiles: (
8
+ /**
9
+ * File path to the entity for which to generate CRUD files.
10
+ *
11
+ * @default undefined -> generate all entities
12
+ */
13
+ file?: string) => Promise<void>;