@postxl/generator 0.52.1 → 0.53.1

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/dist/generator.js CHANGED
@@ -77,7 +77,6 @@ const stub_generator_1 = require("./generators/models/stub.generator");
77
77
  const types_generator_3 = require("./generators/models/types.generator");
78
78
  const meta_1 = require("./lib/meta");
79
79
  const types_1 = require("./lib/schema/types");
80
- const skip_generator_1 = require("./lib/skip-generator");
81
80
  const vfs_1 = require("./lib/vfs");
82
81
  const client_path_1 = require("./prisma/client-path");
83
82
  const parse_1 = require("./prisma/parse");
@@ -168,9 +167,7 @@ function generate({ models, enums, config, prismaClientPath, logger, }) {
168
167
  // Types
169
168
  generated.write(`/${meta.types.filePath}.ts`, (0, types_generator_3.generateModelTypes)({ model, meta }));
170
169
  // Seed
171
- if (!(0, skip_generator_1.skipDecoder)({ model, generatorName: 'seed' })) {
172
- generated.write(`/${meta.seed.filePath}.ts`, (0, seed_generator_1.generateSeedModel)({ model, itemCount: 5, meta, models }));
173
- }
170
+ generated.write(`/${meta.seed.filePath}.ts`, (0, seed_generator_1.generateSeedModel)({ model, itemCount: 5, meta, models }));
174
171
  // Data
175
172
  generated.write(`/${meta.data.stubFilePath}.ts`, (0, stub_generator_1.generateStub)({ model, meta }));
176
173
  generated.write(`/${meta.data.repository.filePath}.ts`, (0, repository_generator_1.generateRepository)({ model, meta }));
@@ -184,15 +181,8 @@ function generate({ models, enums, config, prismaClientPath, logger, }) {
184
181
  // Routes
185
182
  generated.write(`/${meta.trpc.routerFilePath}.ts`, (0, route_generator_1.generateRoute)({ model, meta }));
186
183
  // React
187
- if (!(0, skip_generator_1.skipDecoder)({ model, generatorName: 'react' })) {
188
- yield generated.copy((0, react_generator_2.generateReactComponentsForModel)({ model, meta }), meta.react.folderPath);
189
- }
190
- if (model.attributes.skipGenerators.size === 0) {
191
- logger.log(`- ${model.name} processed`);
192
- }
193
- else {
194
- logger.log(`- ${model.name} processed (skipped generators for: ${[...model.attributes.skipGenerators].join(', ')})`);
195
- }
184
+ yield generated.copy((0, react_generator_2.generateReactComponentsForModel)({ model, meta }), meta.react.folderPath);
185
+ logger.log(`- ${model.name} processed`);
196
186
  }
197
187
  // Generate Enums
198
188
  for (const enumerator of enums.values()) {
@@ -145,26 +145,26 @@ export class ${meta.importExport.importService.name} {
145
145
  getDelta: ({ item, existingItem }: { item: Model; existingItem: Model }) => ${delta_Fields}<Model, ID>
146
146
  }): Promise<Delta_Result<Model, ID>> {
147
147
  if (item.id === undefined || item.id === '') {
148
- return Promise.resolve({ type: '${create.discriminant}' })
148
+ return { type: '${create.discriminant}' }
149
149
  }
150
150
  const existingItem = await getId(item.id)
151
151
 
152
152
  if (!existingItem) {
153
- return Promise.resolve({ type: '${create.discriminant}' })
153
+ return { type: '${create.discriminant}' }
154
154
  }
155
155
 
156
156
  const delta = getDelta({ item, existingItem })
157
157
 
158
158
  if (Object.keys(delta).length > 0) {
159
- return Promise.resolve({ type: '${update.discriminant}', delta, existingItem })
159
+ return { type: '${update.discriminant}', delta, existingItem }
160
160
  }
161
161
 
162
162
  // We do not have a default logic to identify deletions. Implement it here, e.g. using a
163
163
  // custom "Action" field in the Excel table. If it is set to "Delete", we can handle the delete here.
164
- // return Promise.resolve({type: '${delta_Model.delete.discriminant}', existingItem})
164
+ // return {type: '${delta_Model.delete.discriminant}', existingItem}
165
165
 
166
166
  // If we reach this point, we assume the item has not changed
167
- return Promise.resolve({ type: '${unchanged.discriminant}' })
167
+ return { type: '${unchanged.discriminant}' }
168
168
  }
169
169
 
170
170
  private getDelta<Model extends ${dto.genericModel}<ID>, ID extends ${dto.idType}>({
@@ -206,7 +206,7 @@ export class ${meta.importExport.importService.name} {
206
206
  const upsertResult: Delta_Model<Model, ID, ModelErrors>[] = []
207
207
 
208
208
  if (items === undefined || items.length === 0) {
209
- return Promise.resolve(upsertResult)
209
+ return upsertResult
210
210
  }
211
211
 
212
212
  for (const item of items) {
@@ -258,7 +258,7 @@ export class ${meta.importExport.importService.name} {
258
258
  }
259
259
  }
260
260
 
261
- return Promise.resolve(upsertResult)
261
+ return upsertResult
262
262
  }
263
263
 
264
264
  /**
@@ -565,13 +565,11 @@ private async detect${modelMeta.internalSingularNameCapitalized}Delta(
565
565
  properties: [${fieldNames.join(',')}],
566
566
  }),
567
567
  validateCreate: async ({ item }) =>
568
- Promise.resolve(
569
- this.keepErrors([
570
- ${requiredFieldsValidation}
571
- ...(await sharedValidations(item)),
572
- ]),
573
- ),
574
- validateUpdate: async ({ item }) => Promise.resolve(this.keepErrors(await sharedValidations(item))),
568
+ this.keepErrors([
569
+ ${requiredFieldsValidation}
570
+ ...(await sharedValidations(item)),
571
+ ]),
572
+ validateUpdate: async ({ item }) => this.keepErrors(await sharedValidations(item)),
575
573
  validateDelete: ${validateDelete},
576
574
  })
577
575
  }`;
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateSeedMigration = void 0;
4
4
  const imports_1 = require("../../lib/imports");
5
5
  const meta_1 = require("../../lib/meta");
6
- const skip_generator_1 = require("../../lib/skip-generator");
7
6
  /**
8
7
  * Generates the initial migration based on the generated seed data.
9
8
  */
@@ -11,9 +10,6 @@ function generateSeedMigration({ models, meta }) {
11
10
  const imports = imports_1.ImportsGenerator.from(meta.seedData.initialMigrationFilePath);
12
11
  const modelTypes = [];
13
12
  for (const model of models) {
14
- if ((0, skip_generator_1.skipDecoder)({ model, generatorName: 'seed' })) {
15
- continue;
16
- }
17
13
  const modelMeta = (0, meta_1.getModelMetadata)({ model });
18
14
  imports.addImports({
19
15
  [modelMeta.seed.filePath]: [modelMeta.seed.constantName],
@@ -17,6 +17,7 @@ function generateModelBusinessLogicUpdate({ model, meta }) {
17
17
  [meta.data.importPath]: meta.data.repository.className,
18
18
  [schemaMeta.actions.importPath]: schemaMeta.actions.actionExecution.interface,
19
19
  [meta.types.importPath]: [(0, types_1.toAnnotatedTypeName)(model.brandedIdType), (0, types_1.toAnnotatedTypeName)(meta.types.typeName)],
20
+ [meta.businessLogic.view.serviceFilePath]: [meta.businessLogic.view.serviceClassName],
20
21
  [schemaMeta.businessLogic.update.serviceFilePath]: schemaMeta.businessLogic.update.serviceClassName,
21
22
  [schemaMeta.businessLogic.view.serviceFilePath]: schemaMeta.businessLogic.view.serviceClassName,
22
23
  [meta.data.importPath]: [meta.data.repository.className],
@@ -56,7 +57,15 @@ ${actionBlocks.typeDefinitionWithCreateFunction}
56
57
 
57
58
  @Injectable()
58
59
  export class ${meta.businessLogic.update.serviceClassName} {
59
- constructor(${constructorParameters.join(',\n')}) {}
60
+
61
+ /**
62
+ * Instance of the ${meta.userFriendlyName} view service for convenience.
63
+ */
64
+ private view: ${meta.businessLogic.view.serviceClassName}
65
+
66
+ constructor(${constructorParameters.join(',\n')}) {
67
+ this.view = this.${viewServiceClassName}.${meta.businessLogic.view.serviceVariableName}
68
+ }
60
69
 
61
70
  ${actionBlocks.dispatcher}
62
71
 
@@ -120,19 +120,25 @@ export class ${meta.data.repository.className} implements Repository<${model.typ
120
120
 
121
121
  ${mainBlocks.userRepositorySpecificBlocks.rootUserInitializeBlock}
122
122
 
123
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
124
+ // eslint-disable-next-line @typescript-eslint/require-await
123
125
  public async get(id: ${model.brandedIdType} | null): Promise<${model.typeName} | null> {
124
126
  if (id === null) {
125
- return Promise.resolve(null)
127
+ return null
126
128
  }
127
- return Promise.resolve(this.data.get(id) ?? null)
129
+ return this.data.get(id) ?? null
128
130
  }
129
131
 
132
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
133
+ // eslint-disable-next-line @typescript-eslint/require-await
130
134
  public async getAll(): Promise<Map<${model.brandedIdType}, ${model.typeName}>> {
131
- return Promise.resolve(new Map(this.data))
135
+ return new Map(this.data)
132
136
  }
133
137
 
138
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
139
+ // eslint-disable-next-line @typescript-eslint/require-await
134
140
  public async getAllAsArray(): Promise<${model.typeName}[]> {
135
- return Promise.resolve(Array.from(this.data.values()))
141
+ return Array.from(this.data.values())
136
142
  }
137
143
 
138
144
  ${indexBlocks.getterFunctions.join('\n')}
@@ -147,8 +153,10 @@ export class ${meta.data.repository.className} implements Repository<${model.typ
147
153
  return (await this.getAllAsArray()).find(predicate) ?? null
148
154
  }
149
155
 
156
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
157
+ // eslint-disable-next-line @typescript-eslint/require-await
150
158
  public async count(): Promise<number> {
151
- return Promise.resolve(this.data.size)
159
+ return this.data.size
152
160
  }
153
161
 
154
162
  ${mainBlocks.createCode}
@@ -229,6 +237,8 @@ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, schemaMeta, imp
229
237
  constructorCode: '',
230
238
  userRepositorySpecificBlocks,
231
239
  initCode: `
240
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
241
+ // eslint-disable-next-line @typescript-eslint/require-await
232
242
  public async init() {
233
243
  this.data.clear()
234
244
 
@@ -238,8 +248,6 @@ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, schemaMeta, imp
238
248
  ${blocks.indexBlocks.initCode.join('\n')}
239
249
 
240
250
  ${userRepositorySpecificBlocks.initCall}
241
-
242
- return Promise.resolve()
243
251
  }`,
244
252
  reInitCode: `
245
253
  public async reInit({items, execution}: ${methodTypeSignatures.createMany.parameters[0]}): Promise<void> {
@@ -291,7 +299,7 @@ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, schemaMeta, imp
291
299
  })
292
300
 
293
301
  try {
294
- const newItem = await Promise.resolve(this.verifyItem(item))
302
+ const newItem = this.verifyItem(item)
295
303
 
296
304
  this.set(newItem)
297
305
  await execution.finishCreateMutation({ mutationId, createdObject: newItem, entityId: newItem.id })
@@ -314,8 +322,6 @@ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, schemaMeta, imp
314
322
  try {
315
323
  const newItems = items.map((item) => this.verifyItem(item))
316
324
 
317
- await Promise.resolve()
318
-
319
325
  for (const item of newItems) {
320
326
  this.set(item)
321
327
  }
@@ -352,7 +358,7 @@ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, schemaMeta, imp
352
358
 
353
359
  ${blocks.uniqueStringFieldsBlocks.updateCode.join('\n')}
354
360
 
355
- const newItem = await Promise.resolve({ ...existingItem, ...removeUndefinedProperties(item) })
361
+ const newItem = { ...existingItem, ...removeUndefinedProperties(item) }
356
362
  ${model.updatedAtField ? `newItem.${model.updatedAtField.name} = new Date()` : ''}
357
363
 
358
364
  this.remove(existingItem)
@@ -424,8 +430,6 @@ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, schemaMeta, imp
424
430
  sourceObject: existingItem,
425
431
  })
426
432
  try {
427
- await Promise.resolve()
428
-
429
433
  this.remove(existingItem)
430
434
  await execution.finishDeleteMutation({ mutationId })
431
435
  return id
@@ -1159,8 +1163,10 @@ function generateUniqueFieldsBlocks({ model }) {
1159
1163
  for (const f of fields) {
1160
1164
  result.mapDeclarations.push(`'${f.name}': new Map<string, ${model.typeName}>()`);
1161
1165
  result.getByFunctions.push(`
1166
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
1167
+ // eslint-disable-next-line @typescript-eslint/require-await
1162
1168
  public async getBy${(0, string_1.toPascalCase)(f.name)}(${f.name}: string): Promise<${model.typeName} | undefined> {
1163
- return Promise.resolve(this.uniqueIds.${f.name}.get(${(0, string_1.toCamelCase)(f.name)}))
1169
+ return this.uniqueIds.${f.name}.get(${(0, string_1.toCamelCase)(f.name)})
1164
1170
  }`);
1165
1171
  result.clearCode.push(`this.uniqueIds.${f.name}.clear()`);
1166
1172
  result.verifyCode.push(`this.${getEnsureUniqueFnName(f)}(item)`);
@@ -1336,28 +1342,32 @@ function generateRelationsBlocks({ model, imports, }) {
1336
1342
  /**
1337
1343
  * Function to retrieve all ${(0, string_1.pluralize)(model.name)} that are related to a ${r.name}
1338
1344
  */
1345
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
1346
+ // eslint-disable-next-line @typescript-eslint/require-await
1339
1347
  public async ${fieldMeta.getByForeignKeyMethodFnName}(
1340
1348
  id: ${relationModelMeta.types.brandedIdType}
1341
1349
  ): Promise<Map<${model.brandedIdType}, ${model.typeName}>> {
1342
1350
  const result = this.${r.name}Map.get(id)
1343
1351
  if (!result) {
1344
- return Promise.resolve(new Map<${model.brandedIdType}, ${model.typeName}>())
1352
+ return new Map<${model.brandedIdType}, ${model.typeName}>()
1345
1353
  }
1346
- return Promise.resolve(new Map(result))
1354
+ return new Map(result)
1347
1355
  }
1348
1356
 
1349
1357
  /**
1350
1358
  * Function to retrieve all ${model.brandedIdType}s that are related to a ${r.name}
1351
1359
  */
1360
+ // NOTE: The current implementation is synchronous, but it needs to be async to conform to the interface.
1361
+ // eslint-disable-next-line @typescript-eslint/require-await
1352
1362
  public async ${fieldMeta.getByForeignKeyIdsMethodFnName}(
1353
1363
  id: ${relationModelMeta.types.brandedIdType}
1354
1364
  ): Promise<${model.brandedIdType}[]> {
1355
1365
  const s = this.${r.name}Map.get(id)
1356
1366
  if (!s) {
1357
- return Promise.resolve([])
1367
+ return []
1358
1368
  }
1359
1369
 
1360
- return Promise.resolve(Array.from(s.keys()))
1370
+ return Array.from(s.keys())
1361
1371
  }`);
1362
1372
  result.setCode.push(`
1363
1373
  ${!r.isRequired ? `if (item.${r.name}) {` : ''}
@@ -131,7 +131,7 @@ export type ${meta.types.dto.create} = ${schemaMeta.types.dto.create}<${meta.typ
131
131
  export type ${meta.types.dto.update} = ${schemaMeta.types.dto.update}<${meta.types.typeName}, ${model.brandedIdType}>
132
132
 
133
133
  /**
134
- * Data transfer object for upserting an existing ${meta.userFriendlyName} instance.
134
+ * Data transfer object for upserting a new or existing ${meta.userFriendlyName} instance.
135
135
  */
136
136
  export type ${meta.types.dto.upsert} = ${schemaMeta.types.dto.upsert}<${meta.types.typeName}, ${model.brandedIdType}>
137
137
  `;
@@ -1,4 +1,3 @@
1
- import { GeneratorName } from './skip-generator';
2
1
  export type AttributeValue = unknown;
3
2
  export type Attributes = Record<string, AttributeValue>;
4
3
  export type ModelAttributes = {
@@ -37,11 +36,6 @@ export type ModelAttributes = {
37
36
  * The user that is used for system actions.
38
37
  */
39
38
  systemUser?: object;
40
- /**
41
- * Set of generators that should be skipped for this model.
42
- * Schema tag: ´@@Skip("seed", "react")`
43
- */
44
- skipGenerators: Set<GeneratorName>;
45
39
  };
46
40
  export type FieldAttributes = {
47
41
  /**
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getFieldAttributes = exports.getEnumAttributes = exports.getModelAttributes = exports.parseArgumentToStringOrStringArray = exports.parseAttributesFromDocumentation = void 0;
7
7
  const zod_1 = __importDefault(require("zod"));
8
- const skip_generator_1 = require("../lib/skip-generator");
9
8
  const string_1 = require("../lib/utils/string");
10
9
  /**
11
10
  * Parses attributes from a given string using provided prefix.
@@ -75,7 +74,6 @@ function getModelAttributes(model) {
75
74
  schema: zod_1.default.string().optional(),
76
75
  index: zod_1.default.array(zod_1.default.string()).optional(),
77
76
  seed: zod_1.default.string().optional(),
78
- skip: skip_generator_1.skipAttributeDecoder,
79
77
  systemUser: zod_1.default
80
78
  .string()
81
79
  .transform((t) => JSON.parse(t))
@@ -87,7 +85,6 @@ function getModelAttributes(model) {
87
85
  description: obj.description,
88
86
  databaseSchema: obj.schema,
89
87
  index: obj.index,
90
- skipGenerators: obj.skip,
91
88
  systemUser: obj.systemUser,
92
89
  randomSeed: obj.seed !== undefined ? parseInt(obj.seed, 10) : undefined,
93
90
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/generator",
3
- "version": "0.52.1",
3
+ "version": "0.53.1",
4
4
  "main": "./dist/generator.js",
5
5
  "typings": "./dist/generator.d.ts",
6
6
  "bin": {
@@ -1,18 +0,0 @@
1
- import * as z from 'zod';
2
- import { ModelCore } from './schema/schema';
3
- /**
4
- * Identifiers of generators that can be skipped.
5
- */
6
- export type GeneratorName = 'seed' | 'react';
7
- /**
8
- * Decoder to convert a list of generator names to a Set of generator names.
9
- */
10
- export declare const skipAttributeDecoder: z.ZodEffects<z.ZodOptional<z.ZodArray<z.ZodUnion<[z.ZodLiteral<"seed">, z.ZodLiteral<"react">]>, "many">>, Set<"seed" | "react">, ("seed" | "react")[] | undefined>;
11
- export type SkipAttribute = z.infer<typeof skipAttributeDecoder>;
12
- /**
13
- * Returns true if the given generator should be skipped.
14
- */
15
- export declare function skipDecoder({ model, generatorName }: {
16
- model: ModelCore;
17
- generatorName: GeneratorName;
18
- }): boolean;
@@ -1,41 +0,0 @@
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 (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.skipDecoder = exports.skipAttributeDecoder = void 0;
27
- const z = __importStar(require("zod"));
28
- /**
29
- * Decoder to convert a list of generator names to a Set of generator names.
30
- */
31
- exports.skipAttributeDecoder = z
32
- .array(z.union([z.literal('seed'), z.literal('react')]))
33
- .optional()
34
- .transform((t) => new Set(t));
35
- /**
36
- * Returns true if the given generator should be skipped.
37
- */
38
- function skipDecoder({ model, generatorName }) {
39
- return model.attributes.skipGenerators.has(generatorName);
40
- }
41
- exports.skipDecoder = skipDecoder;