@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.
- package/LICENSE +24 -0
- package/bin/api-generator.js +6 -0
- package/lib/apiGenerator.d.ts +1 -0
- package/lib/apiGenerator.js +7 -0
- package/lib/commands/generate/generate-command.d.ts +2 -0
- package/lib/commands/generate/generate-command.js +19 -0
- package/lib/commands/generate/generateCrud/build-options.d.ts +24 -0
- package/lib/commands/generate/generateCrud/build-options.js +144 -0
- package/lib/commands/generate/generateCrud/generate-crud.d.ts +18 -0
- package/lib/commands/generate/generateCrud/generate-crud.js +1092 -0
- package/lib/commands/generate/generateCrud/generate-enum-filter-dto.d.ts +2 -0
- package/lib/commands/generate/generateCrud/generate-enum-filter-dto.js +76 -0
- package/lib/commands/generate/generateCrud/generate-payload-object-types.d.ts +12 -0
- package/lib/commands/generate/generateCrud/generate-payload-object-types.js +38 -0
- package/lib/commands/generate/generateCrud/generate-service-hook-call.d.ts +8 -0
- package/lib/commands/generate/generateCrud/generate-service-hook-call.js +47 -0
- package/lib/commands/generate/generateCrudInput/generate-crud-input.d.ts +12 -0
- package/lib/commands/generate/generateCrudInput/generate-crud-input.js +499 -0
- package/lib/commands/generate/generateCrudSingle/generate-crud-single.d.ts +4 -0
- package/lib/commands/generate/generateCrudSingle/generate-crud-single.js +134 -0
- package/lib/commands/generate/generateFiles.d.ts +13 -0
- package/lib/commands/generate/generateFiles.js +81 -0
- package/lib/commands/generate/utils/build-name-variants.d.ts +9 -0
- package/lib/commands/generate/utils/build-name-variants.js +24 -0
- package/lib/commands/generate/utils/constants.d.ts +2 -0
- package/lib/commands/generate/utils/constants.js +5 -0
- package/lib/commands/generate/utils/find-hooks-service.d.ts +19 -0
- package/lib/commands/generate/utils/find-hooks-service.js +185 -0
- package/lib/commands/generate/utils/generate-imports-code.d.ts +5 -0
- package/lib/commands/generate/utils/generate-imports-code.js +32 -0
- package/lib/commands/generate/utils/ts-morph-helper.d.ts +18 -0
- package/lib/commands/generate/utils/ts-morph-helper.js +237 -0
- package/lib/commands/generate/utils/write-generated-file.d.ts +3 -0
- package/lib/commands/generate/utils/write-generated-file.js +113 -0
- package/lib/commands/generate/utils/write-generated-files.d.ts +7 -0
- package/lib/commands/generate/utils/write-generated-files.js +9 -0
- package/lib/commands/generate/watchMode/handleChildProcess.d.ts +2 -0
- package/lib/commands/generate/watchMode/handleChildProcess.js +26 -0
- package/lib/commands/generate/watchMode/watchMode.d.ts +6 -0
- package/lib/commands/generate/watchMode/watchMode.js +70 -0
- package/package.json +79 -0
|
@@ -0,0 +1,1092 @@
|
|
|
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.generateSortDto = generateSortDto;
|
|
37
|
+
exports.generateInputHandling = generateInputHandling;
|
|
38
|
+
exports.generateCrud = generateCrud;
|
|
39
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
40
|
+
const cms_api_1 = require("@dextinity/cms-api");
|
|
41
|
+
const postgresql_1 = require("@mikro-orm/postgresql");
|
|
42
|
+
const path = __importStar(require("path"));
|
|
43
|
+
const pluralize_1 = require("pluralize");
|
|
44
|
+
const generate_crud_input_1 = require("../generateCrudInput/generate-crud-input");
|
|
45
|
+
const build_name_variants_1 = require("../utils/build-name-variants");
|
|
46
|
+
const constants_1 = require("../utils/constants");
|
|
47
|
+
const find_hooks_service_1 = require("../utils/find-hooks-service");
|
|
48
|
+
const generate_imports_code_1 = require("../utils/generate-imports-code");
|
|
49
|
+
const ts_morph_helper_1 = require("../utils/ts-morph-helper");
|
|
50
|
+
const build_options_1 = require("./build-options");
|
|
51
|
+
const generate_enum_filter_dto_1 = require("./generate-enum-filter-dto");
|
|
52
|
+
const generate_payload_object_types_1 = require("./generate-payload-object-types");
|
|
53
|
+
const generate_service_hook_call_1 = require("./generate-service-hook-call");
|
|
54
|
+
function generateFilterDto({ generatorOptions, metadata, }) {
|
|
55
|
+
const { classNameSingular, fileNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
56
|
+
const { crudFilterProps, targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
57
|
+
const generatedFiles = [];
|
|
58
|
+
const imports = [];
|
|
59
|
+
imports.push({ name: "IsOptional", importPath: "class-validator" });
|
|
60
|
+
imports.push({ name: "ValidateNested", importPath: "class-validator" });
|
|
61
|
+
imports.push({ name: "Type", importPath: "class-transformer" });
|
|
62
|
+
imports.push({ name: "Field", importPath: "@nestjs/graphql" });
|
|
63
|
+
imports.push({ name: "InputType", importPath: "@nestjs/graphql" });
|
|
64
|
+
crudFilterProps.map((prop) => {
|
|
65
|
+
if (prop.type == "EnumArrayType" || prop.enum) {
|
|
66
|
+
const enumName = (0, ts_morph_helper_1.findEnumName)(prop.name, metadata);
|
|
67
|
+
const enumImportPath = (0, ts_morph_helper_1.findEnumImportPath)(enumName, targetDirectory, metadata);
|
|
68
|
+
const enumFilter = (0, generate_enum_filter_dto_1.generateEnumFilterDto)(prop.type == "EnumArrayType" ? "enums" : "enum", enumName, `${targetDirectory}/${enumImportPath}`);
|
|
69
|
+
generatedFiles.push(enumFilter);
|
|
70
|
+
imports.push({
|
|
71
|
+
name: `${enumName}${prop.type == "EnumArrayType" ? "EnumsFilter" : "EnumFilter"}`,
|
|
72
|
+
importPath: `./${path.relative(`${targetDirectory}/dto`, `${enumFilter.targetDirectory}/${enumFilter.name.replace(/\.ts$/, "")}`)}`,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
const filterOut = `
|
|
77
|
+
@InputType()
|
|
78
|
+
export class ${classNameSingular}Filter {
|
|
79
|
+
${crudFilterProps
|
|
80
|
+
.map((prop) => {
|
|
81
|
+
if (prop.type == "EnumArrayType") {
|
|
82
|
+
const enumName = (0, ts_morph_helper_1.findEnumName)(prop.name, metadata);
|
|
83
|
+
return `@Field(() => ${enumName}EnumsFilter, { nullable: true })
|
|
84
|
+
@ValidateNested()
|
|
85
|
+
@IsOptional()
|
|
86
|
+
@Type(() => ${enumName}EnumsFilter)
|
|
87
|
+
${prop.name}?: ${enumName}EnumsFilter;
|
|
88
|
+
`;
|
|
89
|
+
}
|
|
90
|
+
else if (prop.enum) {
|
|
91
|
+
const enumName = (0, ts_morph_helper_1.findEnumName)(prop.name, metadata);
|
|
92
|
+
return `@Field(() => ${enumName}EnumFilter, { nullable: true })
|
|
93
|
+
@ValidateNested()
|
|
94
|
+
@IsOptional()
|
|
95
|
+
@Type(() => ${enumName}EnumFilter)
|
|
96
|
+
${prop.name}?: ${enumName}EnumFilter;
|
|
97
|
+
`;
|
|
98
|
+
}
|
|
99
|
+
else if (prop.type === "string" || prop.type === "text") {
|
|
100
|
+
imports.push({ name: "StringFilter", importPath: "@dextinity/cms-api" });
|
|
101
|
+
return `@Field(() => StringFilter, { nullable: true })
|
|
102
|
+
@ValidateNested()
|
|
103
|
+
@IsOptional()
|
|
104
|
+
@Type(() => StringFilter)
|
|
105
|
+
${prop.name}?: StringFilter;
|
|
106
|
+
`;
|
|
107
|
+
}
|
|
108
|
+
else if (constants_1.numberTypes.includes(prop.type)) {
|
|
109
|
+
imports.push({ name: "NumberFilter", importPath: "@dextinity/cms-api" });
|
|
110
|
+
return `@Field(() => NumberFilter, { nullable: true })
|
|
111
|
+
@ValidateNested()
|
|
112
|
+
@IsOptional()
|
|
113
|
+
@Type(() => NumberFilter)
|
|
114
|
+
${prop.name}?: NumberFilter;
|
|
115
|
+
`;
|
|
116
|
+
}
|
|
117
|
+
else if (prop.type === "boolean" || prop.type === "BooleanType") {
|
|
118
|
+
imports.push({ name: "BooleanFilter", importPath: "@dextinity/cms-api" });
|
|
119
|
+
return `@Field(() => BooleanFilter, { nullable: true })
|
|
120
|
+
@ValidateNested()
|
|
121
|
+
@IsOptional()
|
|
122
|
+
@Type(() => BooleanFilter)
|
|
123
|
+
${prop.name}?: BooleanFilter;
|
|
124
|
+
`;
|
|
125
|
+
}
|
|
126
|
+
else if (prop.type === "DateType") {
|
|
127
|
+
// ISO Date without time
|
|
128
|
+
imports.push({ name: "DateFilter", importPath: "@dextinity/cms-api" });
|
|
129
|
+
return `@Field(() => DateFilter, { nullable: true })
|
|
130
|
+
@ValidateNested()
|
|
131
|
+
@IsOptional()
|
|
132
|
+
@Type(() => DateFilter)
|
|
133
|
+
${prop.name}?: DateFilter;
|
|
134
|
+
`;
|
|
135
|
+
}
|
|
136
|
+
else if (prop.type === "Date") {
|
|
137
|
+
// DateTime
|
|
138
|
+
imports.push({ name: "DateTimeFilter", importPath: "@dextinity/cms-api" });
|
|
139
|
+
return `@Field(() => DateTimeFilter, { nullable: true })
|
|
140
|
+
@ValidateNested()
|
|
141
|
+
@IsOptional()
|
|
142
|
+
@Type(() => DateTimeFilter)
|
|
143
|
+
${prop.name}?: DateTimeFilter;
|
|
144
|
+
`;
|
|
145
|
+
}
|
|
146
|
+
else if (prop.kind === "m:1") {
|
|
147
|
+
imports.push({ name: "ManyToOneFilter", importPath: "@dextinity/cms-api" });
|
|
148
|
+
return `@Field(() => ManyToOneFilter, { nullable: true })
|
|
149
|
+
@ValidateNested()
|
|
150
|
+
@IsOptional()
|
|
151
|
+
@Type(() => ManyToOneFilter)
|
|
152
|
+
${prop.name}?: ManyToOneFilter;
|
|
153
|
+
`;
|
|
154
|
+
}
|
|
155
|
+
else if (prop.kind === "1:m") {
|
|
156
|
+
imports.push({ name: "OneToManyFilter", importPath: "@dextinity/cms-api" });
|
|
157
|
+
return `@Field(() => OneToManyFilter, { nullable: true })
|
|
158
|
+
@ValidateNested()
|
|
159
|
+
@IsOptional()
|
|
160
|
+
@Type(() => OneToManyFilter)
|
|
161
|
+
${prop.name}?: OneToManyFilter;
|
|
162
|
+
`;
|
|
163
|
+
}
|
|
164
|
+
else if (prop.kind === "m:n") {
|
|
165
|
+
imports.push({ name: "ManyToManyFilter", importPath: "@dextinity/cms-api" });
|
|
166
|
+
return `@Field(() => ManyToManyFilter, { nullable: true })
|
|
167
|
+
@ValidateNested()
|
|
168
|
+
@IsOptional()
|
|
169
|
+
@Type(() => ManyToManyFilter)
|
|
170
|
+
${prop.name}?: ManyToManyFilter;
|
|
171
|
+
`;
|
|
172
|
+
}
|
|
173
|
+
else if (prop.type == "uuid") {
|
|
174
|
+
imports.push({ name: "IdFilter", importPath: "@dextinity/cms-api" });
|
|
175
|
+
return `@Field(() => IdFilter, { nullable: true })
|
|
176
|
+
@ValidateNested()
|
|
177
|
+
@IsOptional()
|
|
178
|
+
@Type(() => IdFilter)
|
|
179
|
+
${prop.name}?: IdFilter;
|
|
180
|
+
`;
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
//unsupported type TODO support more
|
|
184
|
+
}
|
|
185
|
+
return "";
|
|
186
|
+
})
|
|
187
|
+
.join("\n")}
|
|
188
|
+
|
|
189
|
+
@Field(() => [${classNameSingular}Filter], { nullable: true })
|
|
190
|
+
@Type(() => ${classNameSingular}Filter)
|
|
191
|
+
@ValidateNested({ each: true })
|
|
192
|
+
@IsOptional()
|
|
193
|
+
and?: ${classNameSingular}Filter[];
|
|
194
|
+
|
|
195
|
+
@Field(() => [${classNameSingular}Filter], { nullable: true })
|
|
196
|
+
@Type(() => ${classNameSingular}Filter)
|
|
197
|
+
@ValidateNested({ each: true })
|
|
198
|
+
@IsOptional()
|
|
199
|
+
or?: ${classNameSingular}Filter[];
|
|
200
|
+
}
|
|
201
|
+
`;
|
|
202
|
+
generatedFiles.push({
|
|
203
|
+
name: `dto/${fileNameSingular}.filter.ts`,
|
|
204
|
+
content: (0, generate_imports_code_1.generateImportsCode)(imports) + filterOut,
|
|
205
|
+
type: "filter",
|
|
206
|
+
});
|
|
207
|
+
return generatedFiles;
|
|
208
|
+
}
|
|
209
|
+
function generateSortDto({ generatorOptions, metadata }) {
|
|
210
|
+
const { classNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
211
|
+
const { crudSortProps } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
212
|
+
const sortOut = `import { SortDirection } from "@dextinity/cms-api";
|
|
213
|
+
import { Field, InputType, registerEnumType } from "@nestjs/graphql";
|
|
214
|
+
import { Type } from "class-transformer";
|
|
215
|
+
import { IsEnum } from "class-validator";
|
|
216
|
+
|
|
217
|
+
export enum ${classNameSingular}SortField {
|
|
218
|
+
${crudSortProps
|
|
219
|
+
.map((prop) => {
|
|
220
|
+
return `${prop.replace(".", "_")} = "${prop.replace(".", "_")}",`;
|
|
221
|
+
})
|
|
222
|
+
.join("\n")}
|
|
223
|
+
}
|
|
224
|
+
registerEnumType(${classNameSingular}SortField, {
|
|
225
|
+
name: "${classNameSingular}SortField",
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
@InputType()
|
|
229
|
+
export class ${classNameSingular}Sort {
|
|
230
|
+
@Field(() => ${classNameSingular}SortField)
|
|
231
|
+
@IsEnum(${classNameSingular}SortField)
|
|
232
|
+
field: ${classNameSingular}SortField;
|
|
233
|
+
|
|
234
|
+
@Field(() => SortDirection, { defaultValue: SortDirection.ASC })
|
|
235
|
+
@IsEnum(SortDirection)
|
|
236
|
+
direction: SortDirection = SortDirection.ASC;
|
|
237
|
+
}
|
|
238
|
+
`;
|
|
239
|
+
return sortOut;
|
|
240
|
+
}
|
|
241
|
+
function generatePaginatedDto({ generatorOptions, metadata }) {
|
|
242
|
+
const { classNamePlural } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
243
|
+
const { targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
244
|
+
const paginatedOut = `import { ObjectType } from "@nestjs/graphql";
|
|
245
|
+
import { PaginatedResponseFactory } from "@dextinity/cms-api";
|
|
246
|
+
|
|
247
|
+
import { ${metadata.className} } from "${path.relative(`${targetDirectory}/dto`, metadata.path).replace(/\.ts$/, "")}";
|
|
248
|
+
|
|
249
|
+
@ObjectType()
|
|
250
|
+
export class Paginated${classNamePlural} extends PaginatedResponseFactory.create(${metadata.className}) {}
|
|
251
|
+
`;
|
|
252
|
+
return paginatedOut;
|
|
253
|
+
}
|
|
254
|
+
function generateArgsDto({ generatorOptions, metadata }) {
|
|
255
|
+
const { classNameSingular, fileNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
256
|
+
const { scopeProp, argsClassName, hasSearchArg, hasSortArg, hasFilterArg, dedicatedResolverArgProps, hasPositionProp, crudSortProps, hasPaging, targetDirectory, } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
257
|
+
const imports = [];
|
|
258
|
+
if (scopeProp && scopeProp.targetMeta) {
|
|
259
|
+
imports.push(generateEntityImport(scopeProp.targetMeta, `${targetDirectory}/dto`));
|
|
260
|
+
}
|
|
261
|
+
let defaultSortField = metadata.props.find((prop) => prop.primary)?.name || "id";
|
|
262
|
+
if (hasPositionProp) {
|
|
263
|
+
defaultSortField = "position";
|
|
264
|
+
}
|
|
265
|
+
else if (metadata.props.some((prop) => prop.name === "createdAt" && prop.type === "Date")) {
|
|
266
|
+
defaultSortField = "createdAt";
|
|
267
|
+
}
|
|
268
|
+
if (!crudSortProps.includes(defaultSortField)) {
|
|
269
|
+
defaultSortField = null;
|
|
270
|
+
}
|
|
271
|
+
const argsOut = `import { ArgsType, Field, IntersectionType, registerEnumType, ID } from "@nestjs/graphql";
|
|
272
|
+
import { Type } from "class-transformer";
|
|
273
|
+
import { IsOptional, IsString, ValidateNested, IsEnum, IsUUID } from "class-validator";
|
|
274
|
+
${hasPaging ? `import { OffsetBasedPaginationArgs, SortDirection } from "@dextinity/cms-api";` : ``}
|
|
275
|
+
${hasPaging && hasFilterArg ? `import { ${classNameSingular}Filter } from "./${fileNameSingular}.filter";` : ``}
|
|
276
|
+
${hasPaging && hasSortArg ? `import { ${classNameSingular}Sort, ${classNameSingular}SortField } from "./${fileNameSingular}.sort";` : ``}
|
|
277
|
+
|
|
278
|
+
${(0, generate_imports_code_1.generateImportsCode)(imports)}
|
|
279
|
+
|
|
280
|
+
@ArgsType()
|
|
281
|
+
export class ${argsClassName}${hasPaging ? ` extends OffsetBasedPaginationArgs` : ""} {
|
|
282
|
+
${scopeProp
|
|
283
|
+
? `
|
|
284
|
+
@Field(() => ${scopeProp.type})
|
|
285
|
+
@ValidateNested()
|
|
286
|
+
@Type(() => ${scopeProp.type})
|
|
287
|
+
scope: ${scopeProp.type};
|
|
288
|
+
`
|
|
289
|
+
: ""}
|
|
290
|
+
|
|
291
|
+
${dedicatedResolverArgProps
|
|
292
|
+
.map((dedicatedResolverArgProp) => {
|
|
293
|
+
if (constants_1.integerTypes.includes(dedicatedResolverArgProp.type)) {
|
|
294
|
+
return `@Field(() => ID)
|
|
295
|
+
@Transform(({ value }) => value.map((id: string) => parseInt(id)))
|
|
296
|
+
@IsInt()
|
|
297
|
+
${dedicatedResolverArgProp.name}: number;`;
|
|
298
|
+
}
|
|
299
|
+
else {
|
|
300
|
+
return `@Field(() => ID)
|
|
301
|
+
@IsUUID()
|
|
302
|
+
${dedicatedResolverArgProp.name}: string;`;
|
|
303
|
+
}
|
|
304
|
+
})
|
|
305
|
+
.join("")}
|
|
306
|
+
|
|
307
|
+
${hasPaging && hasSearchArg
|
|
308
|
+
? `
|
|
309
|
+
@Field({ nullable: true })
|
|
310
|
+
@IsOptional()
|
|
311
|
+
@IsString()
|
|
312
|
+
search?: string;
|
|
313
|
+
`
|
|
314
|
+
: ""}
|
|
315
|
+
|
|
316
|
+
${hasPaging && hasFilterArg
|
|
317
|
+
? `
|
|
318
|
+
@Field(() => ${classNameSingular}Filter, { nullable: true })
|
|
319
|
+
@ValidateNested()
|
|
320
|
+
@Type(() => ${classNameSingular}Filter)
|
|
321
|
+
@IsOptional()
|
|
322
|
+
filter?: ${classNameSingular}Filter;
|
|
323
|
+
`
|
|
324
|
+
: ""}
|
|
325
|
+
|
|
326
|
+
${hasPaging && hasSortArg
|
|
327
|
+
? `
|
|
328
|
+
@Field(() => [${classNameSingular}Sort], { ${defaultSortField === null ? "nullable: true" : `defaultValue: [{ field: ${classNameSingular}SortField.${defaultSortField}, direction: SortDirection.ASC }]`} })
|
|
329
|
+
@ValidateNested({ each: true })
|
|
330
|
+
@Type(() => ${classNameSingular}Sort)
|
|
331
|
+
${defaultSortField === null ? "@IsOptional()" : ""}
|
|
332
|
+
sort${defaultSortField === null ? "?" : ""}: ${classNameSingular}Sort[];
|
|
333
|
+
`
|
|
334
|
+
: ""}
|
|
335
|
+
}
|
|
336
|
+
`;
|
|
337
|
+
return argsOut;
|
|
338
|
+
}
|
|
339
|
+
function generateService({ generatorOptions, metadata }) {
|
|
340
|
+
const { classNameSingular, fileNameSingular, classNamePlural } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
341
|
+
const { hasPositionProp, positionGroupProps, targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
342
|
+
const positionGroupType = positionGroupProps.length
|
|
343
|
+
? `{ ${positionGroupProps
|
|
344
|
+
.map((prop) => {
|
|
345
|
+
const notSupportedReferenceKinds = [postgresql_1.ReferenceKind.ONE_TO_MANY, postgresql_1.ReferenceKind.MANY_TO_MANY];
|
|
346
|
+
if (notSupportedReferenceKinds.includes(prop.kind)) {
|
|
347
|
+
throw new Error(`Not supported reference-type for position-group. ${prop.name}`);
|
|
348
|
+
}
|
|
349
|
+
return `${prop.name}${prop.nullable ? `?` : ``}: ${[postgresql_1.ReferenceKind.MANY_TO_ONE, postgresql_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind) ? "string" : prop.type}`;
|
|
350
|
+
})
|
|
351
|
+
.join(",")} }`
|
|
352
|
+
: false;
|
|
353
|
+
const serviceOut = `import { EntityManager, FilterQuery, raw } from "@mikro-orm/postgresql";
|
|
354
|
+
import { Injectable } from "@nestjs/common";
|
|
355
|
+
|
|
356
|
+
${(0, generate_imports_code_1.generateImportsCode)([generateEntityImport(metadata, targetDirectory)])}
|
|
357
|
+
${(0, generate_imports_code_1.generateImportsCode)(positionGroupProps.reduce((acc, prop) => {
|
|
358
|
+
if (prop.targetMeta) {
|
|
359
|
+
acc.push(generateEntityImport(prop.targetMeta, targetDirectory));
|
|
360
|
+
}
|
|
361
|
+
return acc;
|
|
362
|
+
}, []))}
|
|
363
|
+
import { ${classNameSingular}Filter } from "./dto/${fileNameSingular}.filter";
|
|
364
|
+
|
|
365
|
+
@Injectable()
|
|
366
|
+
export class ${classNamePlural}Service {
|
|
367
|
+
${hasPositionProp
|
|
368
|
+
? `constructor(
|
|
369
|
+
protected readonly entityManager: EntityManager,
|
|
370
|
+
) {}`
|
|
371
|
+
: ""}
|
|
372
|
+
|
|
373
|
+
${hasPositionProp
|
|
374
|
+
? `
|
|
375
|
+
async incrementPositions(${positionGroupProps.length ? `group: ${positionGroupType},` : ``}lowestPosition: number, highestPosition?: number) {
|
|
376
|
+
// Increment positions between newPosition (inclusive) and oldPosition (exclusive)
|
|
377
|
+
await this.entityManager.nativeUpdate(${metadata.className},
|
|
378
|
+
${positionGroupProps.length
|
|
379
|
+
? `{
|
|
380
|
+
$and: [
|
|
381
|
+
{ position: { $gte: lowestPosition, ...(highestPosition ? { $lt: highestPosition } : {}) } },
|
|
382
|
+
this.getPositionGroupCondition(group),
|
|
383
|
+
],
|
|
384
|
+
},`
|
|
385
|
+
: `{ position: { $gte: lowestPosition, ...(highestPosition ? { $lt: highestPosition } : {}) } },`}
|
|
386
|
+
{ position: raw("position + 1") },
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
async decrementPositions(${positionGroupProps.length ? `group: ${positionGroupType},` : ``}lowestPosition: number, highestPosition?: number) {
|
|
391
|
+
// Decrement positions between oldPosition (exclusive) and newPosition (inclusive)
|
|
392
|
+
await this.entityManager.nativeUpdate(${metadata.className},
|
|
393
|
+
${positionGroupProps.length
|
|
394
|
+
? `{
|
|
395
|
+
$and: [
|
|
396
|
+
{ position: { $gt: lowestPosition, ...(highestPosition ? { $lte: highestPosition } : {}) } },
|
|
397
|
+
this.getPositionGroupCondition(group),
|
|
398
|
+
],
|
|
399
|
+
},`
|
|
400
|
+
: `{ position: { $gt: lowestPosition, ...(highestPosition ? { $lte: highestPosition } : {}) } },`}
|
|
401
|
+
{ position: raw("position - 1") },
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async getLastPosition(${positionGroupProps.length ? `group: ${positionGroupType}` : ``}) {
|
|
406
|
+
return this.entityManager.count(${metadata.className}, ${positionGroupProps.length ? `this.getPositionGroupCondition(group)` : `{}`});
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
${positionGroupProps.length
|
|
410
|
+
? `getPositionGroupCondition(group: ${positionGroupType}): FilterQuery<${metadata.className}> {
|
|
411
|
+
return {
|
|
412
|
+
${positionGroupProps.map((field) => `${field.name}: group.${field.name}`).join(",")}
|
|
413
|
+
};
|
|
414
|
+
}`
|
|
415
|
+
: ``}
|
|
416
|
+
`
|
|
417
|
+
: ""}
|
|
418
|
+
}
|
|
419
|
+
`;
|
|
420
|
+
return serviceOut;
|
|
421
|
+
}
|
|
422
|
+
function generateEntityImport(targetMetadata, relativeTo) {
|
|
423
|
+
const libMatch = targetMetadata.path.match(/(packages\/api|@dextinity)\/cms-api\/lib\/(.*)/);
|
|
424
|
+
if (libMatch) {
|
|
425
|
+
// Import from cms-api package
|
|
426
|
+
return {
|
|
427
|
+
name: targetMetadata.className,
|
|
428
|
+
importPath: "@dextinity/cms-api",
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
return {
|
|
432
|
+
name: targetMetadata.className,
|
|
433
|
+
importPath: path.relative(relativeTo, targetMetadata.path).replace(/\.ts$/, ""),
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
function generateInputHandling(options, metadata, generatorOptions, targetDirectory) {
|
|
437
|
+
const { instanceNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
438
|
+
const { blockProps, scopeProp, hasPositionProp, dedicatedResolverArgProps } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
439
|
+
const imports = [];
|
|
440
|
+
const props = metadata.props.filter((prop) => !options.excludeFields || !options.excludeFields.includes(prop.name));
|
|
441
|
+
const relationManyToOneProps = props.filter((prop) => prop.kind === "m:1");
|
|
442
|
+
const relationOneToManyProps = props.filter((prop) => prop.kind === "1:m");
|
|
443
|
+
const relationManyToManyProps = props.filter((prop) => prop.kind === "m:n");
|
|
444
|
+
const relationOneToOneProps = props.filter((prop) => prop.kind === "1:1");
|
|
445
|
+
const inputRelationManyToOneProps = relationManyToOneProps
|
|
446
|
+
.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "input"))
|
|
447
|
+
.filter((prop) => {
|
|
448
|
+
//filter out props that are dedicatedResolverArgProp
|
|
449
|
+
return !dedicatedResolverArgProps.some((dedicatedResolverArgProp) => dedicatedResolverArgProp.name === prop.name);
|
|
450
|
+
})
|
|
451
|
+
.map((prop) => {
|
|
452
|
+
const targetMeta = prop.targetMeta;
|
|
453
|
+
if (!targetMeta) {
|
|
454
|
+
throw new Error("targetMeta is not set for relation");
|
|
455
|
+
}
|
|
456
|
+
imports.push(generateEntityImport(targetMeta, targetDirectory));
|
|
457
|
+
return {
|
|
458
|
+
name: prop.name,
|
|
459
|
+
singularName: (0, pluralize_1.singular)(prop.name),
|
|
460
|
+
nullable: prop.nullable,
|
|
461
|
+
type: prop.type,
|
|
462
|
+
};
|
|
463
|
+
});
|
|
464
|
+
const inputRelationOneToOneProps = relationOneToOneProps
|
|
465
|
+
.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "input"))
|
|
466
|
+
.map((prop) => {
|
|
467
|
+
const targetMeta = prop.targetMeta;
|
|
468
|
+
if (!targetMeta) {
|
|
469
|
+
throw new Error("targetMeta is not set for relation");
|
|
470
|
+
}
|
|
471
|
+
return {
|
|
472
|
+
name: prop.name,
|
|
473
|
+
singularName: (0, pluralize_1.singular)(prop.name),
|
|
474
|
+
nullable: prop.nullable,
|
|
475
|
+
type: prop.type,
|
|
476
|
+
targetMeta,
|
|
477
|
+
};
|
|
478
|
+
});
|
|
479
|
+
const inputRelationToManyProps = [...relationOneToManyProps, ...relationManyToManyProps]
|
|
480
|
+
.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "input"))
|
|
481
|
+
.map((prop) => {
|
|
482
|
+
const targetMeta = prop.targetMeta;
|
|
483
|
+
if (!targetMeta) {
|
|
484
|
+
throw new Error("targetMeta is not set for relation");
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
name: prop.name,
|
|
488
|
+
singularName: (0, pluralize_1.singular)(prop.name),
|
|
489
|
+
nullable: prop.nullable,
|
|
490
|
+
type: prop.type,
|
|
491
|
+
orphanRemoval: prop.orphanRemoval,
|
|
492
|
+
targetMeta,
|
|
493
|
+
};
|
|
494
|
+
});
|
|
495
|
+
const noAssignProps = [...inputRelationToManyProps, ...inputRelationManyToOneProps, ...inputRelationOneToOneProps, ...blockProps];
|
|
496
|
+
const code = `
|
|
497
|
+
${noAssignProps.length
|
|
498
|
+
? `const { ${noAssignProps.map((prop) => `${prop.name}: ${prop.name}Input`).join(", ")}, ...assignInput } = ${options.inputName};`
|
|
499
|
+
: ""}
|
|
500
|
+
${options.assignEntityCode}
|
|
501
|
+
...${noAssignProps.length ? `assignInput` : options.inputName},
|
|
502
|
+
${options.mode == "create" && scopeProp ? `scope,` : ""}${options.mode == "create" && hasPositionProp ? `position,` : ""}
|
|
503
|
+
${options.mode == "create"
|
|
504
|
+
? dedicatedResolverArgProps
|
|
505
|
+
.map((dedicatedResolverArgProp) => {
|
|
506
|
+
return `${dedicatedResolverArgProp.name}: Reference.create(await this.entityManager.findOneOrFail(${dedicatedResolverArgProp.type}, ${dedicatedResolverArgProp.name})), `;
|
|
507
|
+
})
|
|
508
|
+
.join("")
|
|
509
|
+
: ""}
|
|
510
|
+
${options.mode == "create" || options.mode == "updateNested"
|
|
511
|
+
? inputRelationManyToOneProps
|
|
512
|
+
.map((prop) => `${prop.name}: ${prop.nullable ? `${prop.name}Input ? ` : ""}Reference.create(await this.entityManager.findOneOrFail(${prop.type}, ${prop.name}Input))${prop.nullable ? ` : undefined` : ""}, `)
|
|
513
|
+
.join("")
|
|
514
|
+
: ""}
|
|
515
|
+
${options.mode == "create" || options.mode == "updateNested"
|
|
516
|
+
? blockProps.map((prop) => `${prop.name}: ${prop.name}Input.transformToBlockData(),`).join("")
|
|
517
|
+
: ""}
|
|
518
|
+
});
|
|
519
|
+
${inputRelationToManyProps
|
|
520
|
+
.map((prop) => {
|
|
521
|
+
if (prop.orphanRemoval) {
|
|
522
|
+
imports.push(generateEntityImport(prop.targetMeta, targetDirectory));
|
|
523
|
+
const { code, imports: nestedImports } = generateInputHandling({
|
|
524
|
+
mode: "updateNested",
|
|
525
|
+
inputName: `${prop.singularName}Input`,
|
|
526
|
+
// alternative `const ${prop.singularName} = this.entityManager.create(${prop.type}, {` requires back relation to be set
|
|
527
|
+
assignEntityCode: `const ${prop.singularName} = this.entityManager.assign(new ${prop.type}(), {`,
|
|
528
|
+
excludeFields: prop.targetMeta.props
|
|
529
|
+
.filter((prop) => prop.kind == "m:1" && prop.targetMeta == metadata) //filter out referencing back to this entity
|
|
530
|
+
.map((prop) => prop.name),
|
|
531
|
+
}, prop.targetMeta, generatorOptions, targetDirectory);
|
|
532
|
+
imports.push(...nestedImports);
|
|
533
|
+
const isAsync = code.includes("await ");
|
|
534
|
+
return `if (${prop.name}Input) {
|
|
535
|
+
await ${instanceNameSingular}.${prop.name}.loadItems();
|
|
536
|
+
${instanceNameSingular}.${prop.name}.set(
|
|
537
|
+
${isAsync ? `await Promise.all(` : ""}
|
|
538
|
+
${prop.name}Input.map(${isAsync ? `async ` : ""}(${prop.singularName}Input) => {
|
|
539
|
+
${code}
|
|
540
|
+
return ${prop.singularName};
|
|
541
|
+
})
|
|
542
|
+
${isAsync ? `)` : ""}
|
|
543
|
+
);
|
|
544
|
+
}`;
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
return `
|
|
548
|
+
if (${prop.name}Input) {
|
|
549
|
+
const ${prop.name} = await this.entityManager.find(${prop.type}, { id: ${prop.name}Input });
|
|
550
|
+
if (${prop.name}.length != ${prop.name}Input.length) throw new Error("Couldn't find all ${prop.name} that were passed as input");
|
|
551
|
+
await ${instanceNameSingular}.${prop.name}.loadItems();
|
|
552
|
+
${instanceNameSingular}.${prop.name}.set(${prop.name}.map((${prop.singularName}) => Reference.create(${prop.singularName})));
|
|
553
|
+
}`;
|
|
554
|
+
}
|
|
555
|
+
})
|
|
556
|
+
.join("")}
|
|
557
|
+
|
|
558
|
+
${inputRelationOneToOneProps
|
|
559
|
+
.map((prop) => {
|
|
560
|
+
imports.push(generateEntityImport(prop.targetMeta, targetDirectory));
|
|
561
|
+
const { code, imports: nestedImports } = generateInputHandling({
|
|
562
|
+
mode: "updateNested",
|
|
563
|
+
inputName: `${prop.name}Input`,
|
|
564
|
+
assignEntityCode: `this.entityManager.assign(${prop.singularName}, {`,
|
|
565
|
+
excludeFields: prop.targetMeta.props
|
|
566
|
+
.filter((prop) => prop.kind == "1:1" && prop.targetMeta == metadata) //filter out referencing back to this entity
|
|
567
|
+
.map((prop) => prop.name),
|
|
568
|
+
}, prop.targetMeta, generatorOptions, targetDirectory);
|
|
569
|
+
imports.push(...nestedImports);
|
|
570
|
+
return `
|
|
571
|
+
${options.mode != "create" || prop.nullable ? `if (${prop.name}Input) {` : "{"}
|
|
572
|
+
const ${prop.singularName} = ${(options.mode == "update" || options.mode == "updateNested") && prop.nullable
|
|
573
|
+
? `${instanceNameSingular}.${prop.name} ? await ${instanceNameSingular}.${prop.name}.loadOrFail() : new ${prop.type}();`
|
|
574
|
+
: `new ${prop.type}();`}
|
|
575
|
+
${code}
|
|
576
|
+
${options.mode != "create" || prop.nullable ? `}` : "}"}`;
|
|
577
|
+
})
|
|
578
|
+
.join("")}
|
|
579
|
+
${options.mode == "update"
|
|
580
|
+
? inputRelationManyToOneProps
|
|
581
|
+
.map((prop) => `if (${prop.name}Input !== undefined) {
|
|
582
|
+
${instanceNameSingular}.${prop.name} =
|
|
583
|
+
${prop.nullable ? `${prop.name}Input ? ` : ""}
|
|
584
|
+
Reference.create(await this.entityManager.findOneOrFail(${prop.type}, ${prop.name}Input))
|
|
585
|
+
${prop.nullable ? ` : undefined` : ""};
|
|
586
|
+
}`)
|
|
587
|
+
.join("")
|
|
588
|
+
: ""}
|
|
589
|
+
${options.mode == "update"
|
|
590
|
+
? blockProps
|
|
591
|
+
.map((prop) => `
|
|
592
|
+
if (${prop.name}Input) {
|
|
593
|
+
${instanceNameSingular}.${prop.name} = ${prop.name}Input.transformToBlockData();
|
|
594
|
+
}`)
|
|
595
|
+
.join("")
|
|
596
|
+
: ""}
|
|
597
|
+
`;
|
|
598
|
+
return { code, imports };
|
|
599
|
+
}
|
|
600
|
+
function generateNestedEntityResolver({ generatorOptions, metadata }) {
|
|
601
|
+
const { classNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
602
|
+
const { skipScopeCheck, targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
603
|
+
const entityHasRequiredPermission = !!Reflect.getMetadata(cms_api_1.REQUIRED_PERMISSION_METADATA_KEY, metadata.class);
|
|
604
|
+
const imports = [];
|
|
605
|
+
const { imports: fieldImports, code, hasOutputRelations, needsBlocksTransformer, } = generateRelationsFieldResolver({ generatorOptions, metadata });
|
|
606
|
+
if (!hasOutputRelations) {
|
|
607
|
+
return null;
|
|
608
|
+
}
|
|
609
|
+
imports.push(...fieldImports);
|
|
610
|
+
imports.push(generateEntityImport(metadata, targetDirectory));
|
|
611
|
+
return `
|
|
612
|
+
import { ${entityHasRequiredPermission ? "" : "RequiredPermission, "}RootBlockDataScalar, BlocksTransformerService } from "@dextinity/cms-api";
|
|
613
|
+
import { Args, ID, Info, Mutation, Query, Resolver, ResolveField, Parent } from "@nestjs/graphql";
|
|
614
|
+
${(0, generate_imports_code_1.generateImportsCode)(imports)}
|
|
615
|
+
|
|
616
|
+
@Resolver(() => ${metadata.className})
|
|
617
|
+
${entityHasRequiredPermission ? "" : `@RequiredPermission(${JSON.stringify(generatorOptions.requiredPermission)}${skipScopeCheck ? `, { skipScopeCheck: true }` : ""})`}
|
|
618
|
+
export class ${classNameSingular}Resolver {
|
|
619
|
+
${needsBlocksTransformer ? `constructor(protected readonly blocksTransformer: BlocksTransformerService) {}` : ""}
|
|
620
|
+
${code}
|
|
621
|
+
}
|
|
622
|
+
`;
|
|
623
|
+
}
|
|
624
|
+
function generateRelationsFieldResolver({ generatorOptions, metadata }) {
|
|
625
|
+
const { instanceNameSingular } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
626
|
+
const { targetDirectory } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
627
|
+
const relationManyToOneProps = metadata.props.filter((prop) => prop.kind === "m:1");
|
|
628
|
+
const relationOneToManyProps = metadata.props.filter((prop) => prop.kind === "1:m");
|
|
629
|
+
const relationManyToManyProps = metadata.props.filter((prop) => prop.kind === "m:n");
|
|
630
|
+
const relationOneToOneProps = metadata.props.filter((prop) => prop.kind === "1:1");
|
|
631
|
+
const outputRelationManyToOneProps = relationManyToOneProps.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "resolveField"));
|
|
632
|
+
const outputRelationOneToManyProps = relationOneToManyProps.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "resolveField"));
|
|
633
|
+
const outputRelationManyToManyProps = relationManyToManyProps.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "resolveField"));
|
|
634
|
+
const outputRelationOneToOneProps = relationOneToOneProps.filter((prop) => (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "resolveField"));
|
|
635
|
+
for (const prop of metadata.props) {
|
|
636
|
+
if (!(0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "resolveField") &&
|
|
637
|
+
!relationManyToOneProps.includes(prop) &&
|
|
638
|
+
!relationOneToManyProps.includes(prop) &&
|
|
639
|
+
!relationManyToManyProps.includes(prop) &&
|
|
640
|
+
!relationOneToOneProps.includes(prop)) {
|
|
641
|
+
throw new Error(`${prop.name}: @CrudField resolveField=false is only used for relations, for other props simply remove @Field() to disable its output`);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const resolveFieldBlockProps = metadata.props.filter((prop) => {
|
|
645
|
+
return (0, cms_api_1.hasCrudFieldFeature)(metadata.class, prop.name, "resolveField") && prop.type === "RootBlockType";
|
|
646
|
+
});
|
|
647
|
+
const hasOutputRelations = outputRelationManyToOneProps.length > 0 ||
|
|
648
|
+
outputRelationOneToManyProps.length > 0 ||
|
|
649
|
+
outputRelationManyToManyProps.length > 0 ||
|
|
650
|
+
outputRelationOneToOneProps.length > 0;
|
|
651
|
+
const imports = [];
|
|
652
|
+
for (const prop of [...relationManyToOneProps, ...relationOneToManyProps, ...relationManyToManyProps, ...relationOneToOneProps]) {
|
|
653
|
+
if (!prop.targetMeta) {
|
|
654
|
+
throw new Error(`Relation ${prop.name} has targetMeta not set`);
|
|
655
|
+
}
|
|
656
|
+
imports.push(generateEntityImport(prop.targetMeta, targetDirectory));
|
|
657
|
+
}
|
|
658
|
+
for (const prop of resolveFieldBlockProps) {
|
|
659
|
+
const blockName = (0, ts_morph_helper_1.findBlockName)(prop.name, metadata);
|
|
660
|
+
const importPath = (0, ts_morph_helper_1.findBlockImportPath)(blockName, `${targetDirectory}`, metadata);
|
|
661
|
+
imports.push({ name: blockName, importPath });
|
|
662
|
+
}
|
|
663
|
+
const code = `
|
|
664
|
+
${outputRelationManyToOneProps
|
|
665
|
+
.map((prop) => `
|
|
666
|
+
@ResolveField(() => ${prop.type}${prop.nullable ? `, { nullable: true }` : ""})
|
|
667
|
+
async ${prop.name}(@Parent() ${instanceNameSingular}: ${metadata.className}): Promise<${prop.type}${prop.nullable ? ` | undefined` : ""}> {
|
|
668
|
+
return ${instanceNameSingular}.${prop.name}${prop.nullable ? `?` : ""}.loadOrFail();
|
|
669
|
+
}
|
|
670
|
+
`)
|
|
671
|
+
.join("\n")}
|
|
672
|
+
|
|
673
|
+
${outputRelationOneToManyProps
|
|
674
|
+
.map((prop) => `
|
|
675
|
+
@ResolveField(() => [${prop.type}])
|
|
676
|
+
async ${prop.name}(@Parent() ${instanceNameSingular}: ${metadata.className}): Promise<${prop.type}[]> {
|
|
677
|
+
return ${instanceNameSingular}.${prop.name}.loadItems();
|
|
678
|
+
}
|
|
679
|
+
`)
|
|
680
|
+
.join("\n")}
|
|
681
|
+
|
|
682
|
+
${outputRelationManyToManyProps
|
|
683
|
+
.map((prop) => `
|
|
684
|
+
@ResolveField(() => [${prop.type}])
|
|
685
|
+
async ${prop.name}(@Parent() ${instanceNameSingular}: ${metadata.className}): Promise<${prop.type}[]> {
|
|
686
|
+
return ${instanceNameSingular}.${prop.name}.loadItems();
|
|
687
|
+
}
|
|
688
|
+
`)
|
|
689
|
+
.join("\n")}
|
|
690
|
+
|
|
691
|
+
${outputRelationOneToOneProps
|
|
692
|
+
.map((prop) => `
|
|
693
|
+
@ResolveField(() => ${prop.type}${prop.nullable ? `, { nullable: true }` : ""})
|
|
694
|
+
async ${prop.name}(@Parent() ${instanceNameSingular}: ${metadata.className}): Promise<${prop.type}${prop.nullable ? ` | undefined` : ""}> {
|
|
695
|
+
return ${instanceNameSingular}.${prop.name}${prop.nullable ? `?` : ""}.loadOrFail();
|
|
696
|
+
}
|
|
697
|
+
`)
|
|
698
|
+
.join("\n")}
|
|
699
|
+
|
|
700
|
+
${resolveFieldBlockProps
|
|
701
|
+
.map((prop) => `
|
|
702
|
+
@ResolveField(() => RootBlockDataScalar(${(0, ts_morph_helper_1.findBlockName)(prop.name, metadata)}))
|
|
703
|
+
async ${prop.name}(@Parent() ${instanceNameSingular}: ${metadata.className}): Promise<object> {
|
|
704
|
+
return this.blocksTransformer.transformToPlain(${instanceNameSingular}.${prop.name});
|
|
705
|
+
}
|
|
706
|
+
`)
|
|
707
|
+
.join("\n")}
|
|
708
|
+
|
|
709
|
+
`.trim();
|
|
710
|
+
return {
|
|
711
|
+
code,
|
|
712
|
+
imports,
|
|
713
|
+
hasOutputRelations,
|
|
714
|
+
needsBlocksTransformer: resolveFieldBlockProps.length > 0,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
function generateResolver({ generatorOptions, metadata }) {
|
|
718
|
+
const { classNameSingular, fileNameSingular, instanceNameSingular, classNamePlural, fileNamePlural, instanceNamePlural } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
719
|
+
const { scopeProp, skipScopeCheck, argsClassName, argsFileName, hasSlugProp, hasSearchArg, hasSortArg, hasFilterArg, hasPositionProp, positionGroupProps, hasDeletedAtProp, dedicatedResolverArgProps, targetDirectory, hasPaging, hasArgsClass, } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
720
|
+
const imports = [];
|
|
721
|
+
const { code: createInputHandlingCode, imports: createInputHandlingImports } = generateInputHandling({
|
|
722
|
+
mode: "create",
|
|
723
|
+
inputName: "input",
|
|
724
|
+
assignEntityCode: `const ${instanceNameSingular} = this.entityManager.create(${metadata.className}, {`,
|
|
725
|
+
}, metadata, generatorOptions, targetDirectory);
|
|
726
|
+
imports.push(...createInputHandlingImports);
|
|
727
|
+
const { code: updateInputHandlingCode, imports: updateInputHandlingImports } = generateInputHandling({ mode: "update", inputName: "input", assignEntityCode: `${instanceNameSingular}.assign({` }, metadata, generatorOptions, targetDirectory);
|
|
728
|
+
imports.push(...updateInputHandlingImports);
|
|
729
|
+
const { imports: relationsFieldResolverImports, code: relationsFieldResolverCode, needsBlocksTransformer, } = generateRelationsFieldResolver({
|
|
730
|
+
generatorOptions,
|
|
731
|
+
metadata,
|
|
732
|
+
});
|
|
733
|
+
imports.push(...relationsFieldResolverImports);
|
|
734
|
+
imports.push(generateEntityImport(metadata, targetDirectory));
|
|
735
|
+
if (scopeProp && scopeProp.targetMeta) {
|
|
736
|
+
imports.push(generateEntityImport(scopeProp.targetMeta, targetDirectory));
|
|
737
|
+
}
|
|
738
|
+
const hooksService = (0, find_hooks_service_1.findHooksService)({ generatorOptions, metadata, targetDirectory });
|
|
739
|
+
if (hooksService) {
|
|
740
|
+
imports.push(...hooksService.imports);
|
|
741
|
+
if (hooksService.validateCreateInput?.options?.includes("currentUser") ||
|
|
742
|
+
hooksService.validateUpdateInput?.options?.includes("currentUser")) {
|
|
743
|
+
imports.push({ name: "GetCurrentUser", importPath: "@dextinity/cms-api" });
|
|
744
|
+
imports.push({ name: "CurrentUser", importPath: "@dextinity/cms-api" });
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
function generateIdArg(name, metadata) {
|
|
748
|
+
if (constants_1.integerTypes.includes(metadata.properties[name].type)) {
|
|
749
|
+
return `@Args("${name}", { type: () => ID }, { transform: (value) => parseInt(value) }) ${name}: number`;
|
|
750
|
+
}
|
|
751
|
+
else {
|
|
752
|
+
return `@Args("${name}", { type: () => ID }) ${name}: string`;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
const payloadObjectTypes = (0, generate_payload_object_types_1.generatePayloadObjectTypes)({ hooksService, instanceNameSingular, entityName: metadata.className });
|
|
756
|
+
imports.push(...payloadObjectTypes.imports);
|
|
757
|
+
const entityHasRequiredPermission = !!Reflect.getMetadata(cms_api_1.REQUIRED_PERMISSION_METADATA_KEY, metadata.class);
|
|
758
|
+
imports.push({ name: "SortDirection", importPath: "@dextinity/cms-api" });
|
|
759
|
+
if (!entityHasRequiredPermission) {
|
|
760
|
+
imports.push({ name: "RequiredPermission", importPath: "@dextinity/cms-api" });
|
|
761
|
+
}
|
|
762
|
+
imports.push({ name: "AffectedEntity", importPath: "@dextinity/cms-api" });
|
|
763
|
+
imports.push({ name: "validateNotModified", importPath: "@dextinity/cms-api" });
|
|
764
|
+
imports.push({ name: "RootBlockDataScalar", importPath: "@dextinity/cms-api" });
|
|
765
|
+
imports.push({ name: "BlocksTransformerService", importPath: "@dextinity/cms-api" });
|
|
766
|
+
imports.push({ name: "gqlArgsToMikroOrmQuery", importPath: "@dextinity/cms-api" });
|
|
767
|
+
imports.push({ name: "gqlSortToMikroOrmOrderBy", importPath: "@dextinity/cms-api" });
|
|
768
|
+
const resolverOut = `import { EntityManager, FindOptions, ObjectQuery, Reference } from "@mikro-orm/postgresql";
|
|
769
|
+
import { Args, ID, Mutation, Query, Resolver, ResolveField, Parent } from "@nestjs/graphql";
|
|
770
|
+
|
|
771
|
+
${hasPositionProp ? `import { ${classNamePlural}Service } from "./${fileNamePlural}.service";` : ``}
|
|
772
|
+
import { ${classNameSingular}Input, ${classNameSingular}UpdateInput } from "./dto/${fileNameSingular}.input";
|
|
773
|
+
${hasPaging ? `import { Paginated${classNamePlural} } from "./dto/paginated-${fileNamePlural}";` : ""}
|
|
774
|
+
${hasArgsClass ? `import { ${argsClassName} } from "./dto/${argsFileName}";` : ""}
|
|
775
|
+
${(0, generate_imports_code_1.generateImportsCode)(imports)}
|
|
776
|
+
|
|
777
|
+
${payloadObjectTypes.code}
|
|
778
|
+
|
|
779
|
+
@Resolver(() => ${metadata.className})
|
|
780
|
+
${entityHasRequiredPermission ? "" : `@RequiredPermission(${JSON.stringify(generatorOptions.requiredPermission)}${skipScopeCheck ? `, { skipScopeCheck: true }` : ""})`}
|
|
781
|
+
export class ${classNameSingular}Resolver {
|
|
782
|
+
constructor(
|
|
783
|
+
protected readonly entityManager: EntityManager,${hasPositionProp ? `protected readonly ${instanceNamePlural}Service: ${classNamePlural}Service,` : ``}
|
|
784
|
+
${needsBlocksTransformer ? `private readonly blocksTransformer: BlocksTransformerService,` : ""}
|
|
785
|
+
${hooksService ? `protected readonly ${instanceNameSingular}Service: ${hooksService.className},` : ""}
|
|
786
|
+
) {}
|
|
787
|
+
|
|
788
|
+
${generatorOptions.single
|
|
789
|
+
? `
|
|
790
|
+
@Query(() => ${metadata.className})
|
|
791
|
+
@AffectedEntity(${metadata.className})
|
|
792
|
+
async ${instanceNameSingular}(${generateIdArg("id", metadata)}): Promise<${metadata.className}> {
|
|
793
|
+
const ${instanceNameSingular} = await this.entityManager.findOneOrFail(${metadata.className}, id);
|
|
794
|
+
return ${instanceNameSingular};
|
|
795
|
+
}
|
|
796
|
+
`
|
|
797
|
+
: ""}
|
|
798
|
+
|
|
799
|
+
${hasSlugProp
|
|
800
|
+
? `
|
|
801
|
+
@Query(() => ${metadata.className}, { nullable: true })
|
|
802
|
+
async ${instanceNameSingular}BySlug(
|
|
803
|
+
@Args("slug") slug: string
|
|
804
|
+
${scopeProp ? `, @Args("scope", { type: () => ${scopeProp.type} }) scope: ${scopeProp.type}` : ""}
|
|
805
|
+
): Promise<${metadata.className} | null> {
|
|
806
|
+
const ${instanceNameSingular} = await this.entityManager.findOne(${metadata.className}, { slug${scopeProp ? `, scope` : ""}});
|
|
807
|
+
|
|
808
|
+
return ${instanceNameSingular} ?? null;
|
|
809
|
+
}
|
|
810
|
+
`
|
|
811
|
+
: ""}
|
|
812
|
+
|
|
813
|
+
${generatorOptions.list
|
|
814
|
+
? `
|
|
815
|
+
@Query(() => ${hasPaging ? `Paginated${classNamePlural}` : `[${metadata.className}]`})
|
|
816
|
+
${dedicatedResolverArgProps
|
|
817
|
+
.map((dedicatedResolverArgProp) => {
|
|
818
|
+
return `@AffectedEntity(${dedicatedResolverArgProp.targetMeta?.className}, { idArg: "${dedicatedResolverArgProp.name}" })`;
|
|
819
|
+
})
|
|
820
|
+
.join("")}
|
|
821
|
+
async ${instanceNameSingular != instanceNamePlural ? instanceNamePlural : `${instanceNamePlural}List`}(
|
|
822
|
+
${hasArgsClass
|
|
823
|
+
? `@Args() {${Object.entries({
|
|
824
|
+
scope: !!scopeProp,
|
|
825
|
+
...dedicatedResolverArgProps.reduce((acc, dedicatedResolverArgProp) => {
|
|
826
|
+
acc[dedicatedResolverArgProp.name] = true;
|
|
827
|
+
return acc;
|
|
828
|
+
}, {}),
|
|
829
|
+
search: hasPaging && !!hasSearchArg,
|
|
830
|
+
filter: hasPaging && !!hasFilterArg,
|
|
831
|
+
sort: hasPaging && !!hasSortArg,
|
|
832
|
+
offset: hasPaging,
|
|
833
|
+
limit: hasPaging,
|
|
834
|
+
})
|
|
835
|
+
.filter(([key, use]) => use)
|
|
836
|
+
.map(([key]) => key)
|
|
837
|
+
.join(", ")}}: ${argsClassName}`
|
|
838
|
+
: ""}
|
|
839
|
+
): Promise<${hasPaging ? `Paginated${classNamePlural}` : `${metadata.className}[]`}> {
|
|
840
|
+
const where${hasPaging && (hasSearchArg || hasFilterArg)
|
|
841
|
+
? ` = gqlArgsToMikroOrmQuery({ ${hasSearchArg ? `search, ` : ""}${hasFilterArg ? `filter, ` : ""} }, this.entityManager.getMetadata(${metadata.className}));`
|
|
842
|
+
: `: ObjectQuery<${metadata.className}> = {}`}
|
|
843
|
+
${scopeProp ? `where.scope = scope;` : ""}
|
|
844
|
+
${dedicatedResolverArgProps
|
|
845
|
+
.map((dedicatedResolverArgProp) => {
|
|
846
|
+
return `where.${dedicatedResolverArgProp.name} = ${dedicatedResolverArgProp.name};`;
|
|
847
|
+
})
|
|
848
|
+
.join("\n")}
|
|
849
|
+
|
|
850
|
+
const options: FindOptions<${metadata.className}> = { ${hasPaging ? "offset, limit" : ""}};
|
|
851
|
+
|
|
852
|
+
${hasPaging && hasSortArg
|
|
853
|
+
? `if (sort) {
|
|
854
|
+
options.orderBy = gqlSortToMikroOrmOrderBy(sort);
|
|
855
|
+
}`
|
|
856
|
+
: ""}
|
|
857
|
+
|
|
858
|
+
${hasPaging
|
|
859
|
+
? `const [entities, totalCount] = await this.entityManager.findAndCount(${metadata.className}, where, options);
|
|
860
|
+
return new Paginated${classNamePlural}(entities, totalCount);`
|
|
861
|
+
: `const entities = await this.entityManager.find(${metadata.className}, where, options);
|
|
862
|
+
return entities;`}
|
|
863
|
+
}
|
|
864
|
+
`
|
|
865
|
+
: ""}
|
|
866
|
+
|
|
867
|
+
${generatorOptions.create
|
|
868
|
+
? `
|
|
869
|
+
|
|
870
|
+
@Mutation(() => ${payloadObjectTypes.createPayloadType || metadata.className})
|
|
871
|
+
${dedicatedResolverArgProps
|
|
872
|
+
.map((dedicatedResolverArgProp) => {
|
|
873
|
+
return `@AffectedEntity(${dedicatedResolverArgProp.targetMeta?.className}, { idArg: "${dedicatedResolverArgProp.name}" })`;
|
|
874
|
+
})
|
|
875
|
+
.join("")}
|
|
876
|
+
async create${classNameSingular}(
|
|
877
|
+
${scopeProp ? `@Args("scope", { type: () => ${scopeProp.type} }) scope: ${scopeProp.type},` : ""}${dedicatedResolverArgProps
|
|
878
|
+
.map((dedicatedResolverArgProp) => {
|
|
879
|
+
return `${generateIdArg(dedicatedResolverArgProp.name, metadata)}, `;
|
|
880
|
+
})
|
|
881
|
+
.join("")}@Args("input", { type: () => ${classNameSingular}Input }) input: ${classNameSingular}Input
|
|
882
|
+
${hooksService?.validateCreateInput?.options?.includes("currentUser") ? `, @GetCurrentUser() user: CurrentUser` : ""}
|
|
883
|
+
): Promise<${payloadObjectTypes.createPayloadType || metadata.className}> {
|
|
884
|
+
${(0, generate_service_hook_call_1.generateServiceHookCall)("validateCreateInput", { hooksService, instanceNameSingular, scopeProp, dedicatedResolverArgProps })}
|
|
885
|
+
|
|
886
|
+
${
|
|
887
|
+
// use local position-var because typescript does not narrow down input.position, keeping "| undefined" typing resulting in typescript error in create-function
|
|
888
|
+
hasPositionProp
|
|
889
|
+
? `
|
|
890
|
+
const lastPosition = await this.${instanceNamePlural}Service.getLastPosition(${positionGroupProps.length
|
|
891
|
+
? `{ ${positionGroupProps
|
|
892
|
+
.map((prop) => prop.name === "scope"
|
|
893
|
+
? `scope`
|
|
894
|
+
: dedicatedResolverArgProps.find((dedicatedResolverArgProp) => dedicatedResolverArgProp.name === prop.name) !==
|
|
895
|
+
undefined
|
|
896
|
+
? prop.name
|
|
897
|
+
: `${prop.name}: input.${prop.name}`)
|
|
898
|
+
.join(",")} }`
|
|
899
|
+
: ``});
|
|
900
|
+
let position = input.position;
|
|
901
|
+
if (position !== undefined && position < lastPosition + 1) {
|
|
902
|
+
await this.${instanceNamePlural}Service.incrementPositions(${positionGroupProps.length
|
|
903
|
+
? `{ ${positionGroupProps
|
|
904
|
+
.map((prop) => prop.name === "scope"
|
|
905
|
+
? `scope`
|
|
906
|
+
: dedicatedResolverArgProps.find((dedicatedResolverArgProp) => dedicatedResolverArgProp.name === prop.name) !==
|
|
907
|
+
undefined
|
|
908
|
+
? prop.name
|
|
909
|
+
: `${prop.name}: input.${prop.name}`)
|
|
910
|
+
.join(",")} }, `
|
|
911
|
+
: ``}position);
|
|
912
|
+
} else {
|
|
913
|
+
position = lastPosition + 1;
|
|
914
|
+
}`
|
|
915
|
+
: ""}
|
|
916
|
+
|
|
917
|
+
${createInputHandlingCode}
|
|
918
|
+
|
|
919
|
+
await this.entityManager.flush();
|
|
920
|
+
|
|
921
|
+
return ${payloadObjectTypes.createPayloadType ? `{ ${instanceNameSingular}, errors: [] }` : instanceNameSingular};
|
|
922
|
+
}
|
|
923
|
+
`
|
|
924
|
+
: ""}
|
|
925
|
+
|
|
926
|
+
${generatorOptions.update
|
|
927
|
+
? `
|
|
928
|
+
@Mutation(() => ${payloadObjectTypes.updatePayloadType || metadata.className})
|
|
929
|
+
@AffectedEntity(${metadata.className})
|
|
930
|
+
async update${classNameSingular}(
|
|
931
|
+
${generateIdArg("id", metadata)},
|
|
932
|
+
@Args("input", { type: () => ${classNameSingular}UpdateInput }) input: ${classNameSingular}UpdateInput
|
|
933
|
+
${hooksService?.validateUpdateInput?.options?.includes("currentUser") ? `, @GetCurrentUser() user: CurrentUser` : ""}
|
|
934
|
+
): Promise<${payloadObjectTypes.updatePayloadType || metadata.className}> {
|
|
935
|
+
const ${instanceNameSingular} = await this.entityManager.findOneOrFail(${metadata.className}, id);
|
|
936
|
+
${(0, generate_service_hook_call_1.generateServiceHookCall)("validateUpdateInput", { hooksService, instanceNameSingular, scopeProp, dedicatedResolverArgProps })}
|
|
937
|
+
|
|
938
|
+
${hasPositionProp
|
|
939
|
+
? `
|
|
940
|
+
if (input.position !== undefined) {
|
|
941
|
+
const lastPosition = await this.${instanceNamePlural}Service.getLastPosition(${positionGroupProps.length
|
|
942
|
+
? `{ ${positionGroupProps
|
|
943
|
+
.map((prop) => `${prop.name}: ${instanceNameSingular}.${prop.name}${[postgresql_1.ReferenceKind.MANY_TO_ONE, postgresql_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind)
|
|
944
|
+
? `${prop.nullable ? `?` : ``}.id`
|
|
945
|
+
: ``}`)
|
|
946
|
+
.join(",")} }`
|
|
947
|
+
: ``});
|
|
948
|
+
if (input.position > lastPosition) {
|
|
949
|
+
input.position = lastPosition;
|
|
950
|
+
}
|
|
951
|
+
if (${instanceNameSingular}.position < input.position) {
|
|
952
|
+
await this.${instanceNamePlural}Service.decrementPositions(${positionGroupProps.length
|
|
953
|
+
? `{ ${positionGroupProps
|
|
954
|
+
.map((prop) => `${prop.name}: ${instanceNameSingular}.${prop.name}${[postgresql_1.ReferenceKind.MANY_TO_ONE, postgresql_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind)
|
|
955
|
+
? `${prop.nullable ? `?` : ``}.id`
|
|
956
|
+
: ``}`)
|
|
957
|
+
.join(",")} },`
|
|
958
|
+
: ``}${instanceNameSingular}.position, input.position);
|
|
959
|
+
} else if (${instanceNameSingular}.position > input.position) {
|
|
960
|
+
await this.${instanceNamePlural}Service.incrementPositions(${positionGroupProps.length
|
|
961
|
+
? `{ ${positionGroupProps
|
|
962
|
+
.map((prop) => `${prop.name}: ${instanceNameSingular}.${prop.name}${[postgresql_1.ReferenceKind.MANY_TO_ONE, postgresql_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind)
|
|
963
|
+
? `${prop.nullable ? `?` : ``}.id`
|
|
964
|
+
: ``}`)
|
|
965
|
+
.join(",")} },`
|
|
966
|
+
: ``}input.position, ${instanceNameSingular}.position);
|
|
967
|
+
}
|
|
968
|
+
}`
|
|
969
|
+
: ""}
|
|
970
|
+
|
|
971
|
+
${updateInputHandlingCode}
|
|
972
|
+
|
|
973
|
+
await this.entityManager.flush();
|
|
974
|
+
|
|
975
|
+
return ${payloadObjectTypes.updatePayloadType ? `{ ${instanceNameSingular}, errors: [] }` : instanceNameSingular};
|
|
976
|
+
}
|
|
977
|
+
`
|
|
978
|
+
: ""}
|
|
979
|
+
|
|
980
|
+
${generatorOptions.delete
|
|
981
|
+
? `
|
|
982
|
+
@Mutation(() => Boolean)
|
|
983
|
+
@AffectedEntity(${metadata.className})
|
|
984
|
+
async delete${metadata.className}(${generateIdArg("id", metadata)}): Promise<boolean> {
|
|
985
|
+
const ${instanceNameSingular} = await this.entityManager.findOneOrFail(${metadata.className}, id);
|
|
986
|
+
${hasDeletedAtProp ? `${instanceNameSingular}.assign({ deletedAt: new Date() });` : `this.entityManager.remove(${instanceNameSingular});`}
|
|
987
|
+
${hasPositionProp
|
|
988
|
+
? `await this.${instanceNamePlural}Service.decrementPositions(${positionGroupProps.length
|
|
989
|
+
? `{ ${positionGroupProps
|
|
990
|
+
.map((prop) => `${prop.name}: ${instanceNameSingular}.${prop.name}${[postgresql_1.ReferenceKind.MANY_TO_ONE, postgresql_1.ReferenceKind.ONE_TO_ONE].includes(prop.kind)
|
|
991
|
+
? `${prop.nullable ? `?` : ``}.id`
|
|
992
|
+
: ``}`)
|
|
993
|
+
.join(",")} },`
|
|
994
|
+
: ``}${instanceNameSingular}.position);`
|
|
995
|
+
: ""}
|
|
996
|
+
await this.entityManager.flush();
|
|
997
|
+
return true;
|
|
998
|
+
}
|
|
999
|
+
`
|
|
1000
|
+
: ""}
|
|
1001
|
+
|
|
1002
|
+
${relationsFieldResolverCode}
|
|
1003
|
+
}
|
|
1004
|
+
`;
|
|
1005
|
+
return resolverOut;
|
|
1006
|
+
}
|
|
1007
|
+
async function generateCrud(generatorOptionsParam, metadata) {
|
|
1008
|
+
const generatorOptions = {
|
|
1009
|
+
...generatorOptionsParam,
|
|
1010
|
+
create: generatorOptionsParam.create ?? true,
|
|
1011
|
+
update: generatorOptionsParam.update ?? true,
|
|
1012
|
+
delete: generatorOptionsParam.delete ?? true,
|
|
1013
|
+
list: generatorOptionsParam.list ?? true,
|
|
1014
|
+
single: generatorOptionsParam.single ?? true,
|
|
1015
|
+
};
|
|
1016
|
+
if (!generatorOptions.create && !generatorOptions.update && !generatorOptions.delete && !generatorOptions.list && !generatorOptions.single) {
|
|
1017
|
+
throw new Error("At least one of create, update, delete, list or single must be true");
|
|
1018
|
+
}
|
|
1019
|
+
const generatedFiles = [];
|
|
1020
|
+
const { fileNameSingular, fileNamePlural } = (0, build_name_variants_1.buildNameVariants)(metadata);
|
|
1021
|
+
const { hasFilterArg, hasSortArg, argsFileName, hasPositionProp, hasPaging, hasArgsClass } = (0, build_options_1.buildOptions)(metadata, generatorOptions);
|
|
1022
|
+
async function generateCrudResolver() {
|
|
1023
|
+
if (hasPaging && hasFilterArg) {
|
|
1024
|
+
generatedFiles.push(...generateFilterDto({ generatorOptions, metadata }));
|
|
1025
|
+
}
|
|
1026
|
+
if (hasPaging && hasSortArg) {
|
|
1027
|
+
generatedFiles.push({
|
|
1028
|
+
name: `dto/${fileNameSingular}.sort.ts`,
|
|
1029
|
+
content: generateSortDto({ generatorOptions, metadata }),
|
|
1030
|
+
type: "sort",
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
if (hasPaging) {
|
|
1034
|
+
generatedFiles.push({
|
|
1035
|
+
name: `dto/paginated-${fileNamePlural}.ts`,
|
|
1036
|
+
content: generatePaginatedDto({ generatorOptions, metadata }),
|
|
1037
|
+
type: "sort",
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
if (hasArgsClass) {
|
|
1041
|
+
generatedFiles.push({
|
|
1042
|
+
name: `dto/${argsFileName}.ts`,
|
|
1043
|
+
content: generateArgsDto({ generatorOptions, metadata }),
|
|
1044
|
+
type: "args",
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
if (hasPositionProp) {
|
|
1048
|
+
generatedFiles.push({
|
|
1049
|
+
name: `${fileNamePlural}.service.ts`,
|
|
1050
|
+
content: generateService({ generatorOptions, metadata }),
|
|
1051
|
+
type: "service",
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
generatedFiles.push({
|
|
1055
|
+
name: `${fileNameSingular}.resolver.ts`,
|
|
1056
|
+
content: generateResolver({ generatorOptions, metadata }),
|
|
1057
|
+
type: "resolver",
|
|
1058
|
+
});
|
|
1059
|
+
metadata.props
|
|
1060
|
+
.filter((prop) => {
|
|
1061
|
+
if (prop.kind === "1:m" && prop.orphanRemoval) {
|
|
1062
|
+
if (!prop.targetMeta) {
|
|
1063
|
+
throw new Error(`Target metadata not set`);
|
|
1064
|
+
}
|
|
1065
|
+
const hasOwnCrudGenerator = Reflect.getMetadata(cms_api_1.CRUD_GENERATOR_METADATA_KEY, prop.targetMeta.class);
|
|
1066
|
+
if (!hasOwnCrudGenerator) {
|
|
1067
|
+
//generate nested resolver only if target entity has no own crud generator
|
|
1068
|
+
return true;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
})
|
|
1072
|
+
.forEach((prop) => {
|
|
1073
|
+
if (!prop.targetMeta) {
|
|
1074
|
+
throw new Error(`Target metadata not set`);
|
|
1075
|
+
}
|
|
1076
|
+
const { fileNameSingular } = (0, build_name_variants_1.buildNameVariants)(prop.targetMeta);
|
|
1077
|
+
const content = generateNestedEntityResolver({ generatorOptions, metadata: prop.targetMeta });
|
|
1078
|
+
//can be null if no relations exist
|
|
1079
|
+
if (content) {
|
|
1080
|
+
generatedFiles.push({
|
|
1081
|
+
name: `${fileNameSingular}.resolver.ts`,
|
|
1082
|
+
content,
|
|
1083
|
+
type: "resolver",
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
});
|
|
1087
|
+
return generatedFiles;
|
|
1088
|
+
}
|
|
1089
|
+
const crudInput = await (0, generate_crud_input_1.generateCrudInput)(generatorOptions, metadata);
|
|
1090
|
+
const crudResolver = await generateCrudResolver();
|
|
1091
|
+
return [...crudInput, ...crudResolver];
|
|
1092
|
+
}
|