@postxl/generator 0.27.0 → 0.27.2

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.
@@ -2,16 +2,6 @@ import { ModelMetaData } from '../../lib/meta';
2
2
  import { Model } from '../../lib/schema/schema';
3
3
  /**
4
4
  * Generates repository data structure for a given model.
5
- * Based on the model, the repository is generated slightly differently, based on:
6
- * - if the model has a default field, the repository will have a public variable "defaultValue"
7
- * that is set and verified during init
8
- * - if the model has a generated id, the repository will have a function "generateNextId" that
9
- * is used to generate the next id. The `create` and `createMany` functions will use this function
10
- * and allow being called with an id.
11
- * - unique string fields are ensured to be unique
12
- * - max length string fields are ensured to not exceed their max length
13
- * - index for fields marked with index attribute
14
- * - relations are indexed by the foreign key
15
5
  */
16
6
  export declare function generateRepository({ model, meta }: {
17
7
  model: Model;
@@ -10,16 +10,6 @@ const jsdoc_1 = require("../../lib/utils/jsdoc");
10
10
  const string_1 = require("../../lib/utils/string");
11
11
  /**
12
12
  * Generates repository data structure for a given model.
13
- * Based on the model, the repository is generated slightly differently, based on:
14
- * - if the model has a default field, the repository will have a public variable "defaultValue"
15
- * that is set and verified during init
16
- * - if the model has a generated id, the repository will have a function "generateNextId" that
17
- * is used to generate the next id. The `create` and `createMany` functions will use this function
18
- * and allow being called with an id.
19
- * - unique string fields are ensured to be unique
20
- * - max length string fields are ensured to not exceed their max length
21
- * - index for fields marked with index attribute
22
- * - relations are indexed by the foreign key
23
13
  */
24
14
  function generateRepository({ model, meta }) {
25
15
  const { idField } = model;
@@ -30,13 +20,63 @@ function generateRepository({ model, meta }) {
30
20
  })
31
21
  .addImport({
32
22
  items: [(0, types_1.toClassName)('Repository')],
23
+ // TODO: Unify DataLib Imports https://github.com/PostXL/PostXL/issues/344!
33
24
  from: (0, types_1.toFileName)(model.schemaConfig.paths.dataLibPath + 'repository.type'),
25
+ })
26
+ .addImport({
27
+ items: [meta.types.toBrandedIdTypeFnName],
28
+ from: meta.types.importPath,
34
29
  });
35
- const blocks = generateBlocks({ model, meta, imports });
36
- const mainBlocks = generateMainBuildingBlocks({ model, meta, imports, blocks });
30
+ // NOTE: We first generate different parts of the code responisble for a particular task
31
+ // and then we combine them into the final code block.
32
+ //
33
+ // Based on the model, the repository is generated slightly differently:
34
+ // 1.) if the model has a default field, the repository will have a public variable "defaultValue"
35
+ // that is set and verified during init,
36
+ // 2.) if the model has a generated id, the repository will have a function "generateNextId" that
37
+ // is used to generate the next id. The `create` and `createMany` functions will use this function
38
+ // and allow being called with an id,
39
+ // 3.) unique string fields are ensured to be unique,
40
+ // 4.) max length string fields are ensured to not exceed their max length,
41
+ // 5.) index for fields marked with index attribute,
42
+ // 6.) relations are indexed by the foreign key.
43
+ const idBlocks = generateIdBlocks({ model, meta });
44
+ const defaultValueBlocks = generateDefaultBlocks({ model, meta });
45
+ const uniqueStringFieldsBlocks = generateUniqueFieldsBlocks({ model, meta });
46
+ const maxLengthBlocks = generateMaxLengthBlocks({ model, meta });
47
+ const indexBlocks = generateIndexBlocks({ model, meta, imports });
48
+ const relationsBlocks = generateRelationsBlocks({ model, meta, imports });
49
+ let mainBlocks;
50
+ if (model.attributes.inMemoryOnly) {
51
+ mainBlocks = _generateMainBuildingBlocks_InMemoryOnly({
52
+ model,
53
+ meta,
54
+ blocks: {
55
+ uniqueStringFieldsBlocks,
56
+ defaultValueBlocks,
57
+ idBlocks,
58
+ indexBlocks,
59
+ maxLengthBlocks,
60
+ },
61
+ });
62
+ }
63
+ else {
64
+ mainBlocks = generateMainBuildingBlocks_InDatabase({
65
+ model,
66
+ meta,
67
+ imports,
68
+ blocks: {
69
+ uniqueStringFieldsBlocks,
70
+ defaultValueBlocks,
71
+ idBlocks,
72
+ indexBlocks,
73
+ maxLengthBlocks,
74
+ },
75
+ });
76
+ }
37
77
  return `
38
78
  import { Injectable, Logger } from '@nestjs/common'
39
- ${blocks.id.libraryImports}
79
+ ${idBlocks.libraryImports}
40
80
  ${imports.generate()}
41
81
 
42
82
  @Injectable()
@@ -44,17 +84,17 @@ export class ${meta.data.repositoryClassName} implements Repository<${model.type
44
84
  protected data: Map<${model.brandedIdType}, ${model.typeName}> = new Map()
45
85
  protected logger = new Logger(${meta.data.repositoryClassName}.name)
46
86
 
47
- ${blocks.relations.mapDeclarations.join('\n')}
87
+ ${relationsBlocks.mapDeclarations.join('\n')}
48
88
 
49
- ${blocks.default.publicVariableDeclaration}
89
+ ${defaultValueBlocks.publicVariableDeclaration}
50
90
 
51
- ${blocks.id.generateNextIdFunctionName}
91
+ ${idBlocks.generateNextIdFunctionName}
52
92
 
53
93
  protected uniqueIds = {
54
- ${blocks.uniqueStringFields.mapDeclarations.join(',\n')}
94
+ ${uniqueStringFieldsBlocks.mapDeclarations.join(',\n')}
55
95
  }
56
96
 
57
- ${blocks.index.nestedMapDeclarations.join('\n')}
97
+ ${indexBlocks.nestedMapDeclarations.join('\n')}
58
98
 
59
99
  ${mainBlocks.constructorCode}
60
100
 
@@ -72,14 +112,14 @@ export class ${meta.data.repositoryClassName} implements Repository<${model.type
72
112
  }
73
113
 
74
114
  public getAll(): Map<${model.brandedIdType}, ${model.typeName}> {
75
- return this.data
115
+ return new Map(this.data)
76
116
  }
77
117
 
78
118
  public getAllAsArray(): ${model.typeName}[] {
79
119
  return Array.from(this.data.values())
80
120
  }
81
121
 
82
- ${blocks.index.getterFunctions.join('\n')}
122
+ ${indexBlocks.getterFunctions.join('\n')}
83
123
 
84
124
  public filter(predicate: (item: ${model.typeName}) => boolean): ${model.typeName}[] {
85
125
  return this.getAllAsArray().filter(predicate)
@@ -95,17 +135,18 @@ export class ${meta.data.repositoryClassName} implements Repository<${model.type
95
135
 
96
136
  /**${(0, jsdoc_1.convertToJsDocComments)([
97
137
  `Checks that item has the ${idField.name} field.`,
98
- `In case none exists, ${blocks.id.verifyFunctionComment}`,
99
- blocks.uniqueStringFields.verifyFunctionComment,
100
- blocks.maxLength.verifyFunctionComment,
138
+ `In case none exists, ${idBlocks.verifyFunctionComment}`,
139
+ uniqueStringFieldsBlocks.verifyFunctionComment,
140
+ maxLengthBlocks.verifyFunctionComment,
101
141
  ])}
102
142
  */
103
- private verifyItem(item: ${blocks.id.verifyFunctionParameterType}): ${model.typeName} {
104
- ${blocks.id.verifyCode}
105
143
 
106
- ${blocks.maxLength.verifyCode.join('\n')}
144
+ private verifyItem(item: ${idBlocks.verifyFunctionParameterType}): ${model.typeName} {
145
+ ${idBlocks.verifyCode}
146
+
147
+ ${maxLengthBlocks.verifyCode.join('\n')}
107
148
 
108
- ${blocks.uniqueStringFields.verifyCode.join('\n')}
149
+ ${uniqueStringFieldsBlocks.verifyCode.join('\n')}
109
150
 
110
151
  return {
111
152
  ${idField.name},
@@ -130,25 +171,25 @@ export class ${meta.data.repositoryClassName} implements Repository<${model.type
130
171
 
131
172
  ${mainBlocks.deleteCode}
132
173
 
133
- ${blocks.relations.getterFunctions.join('\n')}
174
+ ${relationsBlocks.getterFunctions.join('\n')}
134
175
 
135
- ${blocks.maxLength.ensureMaxLengthFunctions.join('\n')}
176
+ ${maxLengthBlocks.ensureMaxLengthFunctions.join('\n')}
136
177
 
137
- ${blocks.uniqueStringFields.ensureUniqueFunctions.join('\n\n')}
178
+ ${uniqueStringFieldsBlocks.ensureUniqueFunctions.join('\n\n')}
138
179
 
139
180
  /**
140
181
  * Function that adds/updates a given item to the internal data store, indexes, etc.
141
182
  */
142
183
  private set(item: ${model.typeName}): void {
143
- ${blocks.id.setCode}
184
+ ${idBlocks.setCode}
144
185
 
145
186
  this.data.set(item.id, item)
146
187
 
147
- ${blocks.uniqueStringFields.setCode.join('\n')}
188
+ ${uniqueStringFieldsBlocks.setCode.join('\n')}
148
189
 
149
- ${blocks.relations.setCode.join('\n')}
190
+ ${relationsBlocks.setCode.join('\n')}
150
191
 
151
- ${blocks.index.setCode.join('\n')}
192
+ ${indexBlocks.setCode.join('\n')}
152
193
  }
153
194
 
154
195
  /**
@@ -156,11 +197,11 @@ export class ${meta.data.repositoryClassName} implements Repository<${model.type
156
197
  */
157
198
  private remove(item: ${model.typeName}): void {
158
199
  this.data.delete(item.id)
159
- ${blocks.uniqueStringFields.removeCode.join('\n')}
200
+ ${uniqueStringFieldsBlocks.removeCode.join('\n')}
160
201
 
161
- ${blocks.relations.removeCode.join('\n')}
202
+ ${relationsBlocks.removeCode.join('\n')}
162
203
 
163
- ${blocks.index.removeCode.join('\n')}
204
+ ${indexBlocks.removeCode.join('\n')}
164
205
  }
165
206
 
166
207
  ${mainBlocks.databaseDecoderCode}
@@ -178,26 +219,20 @@ function generateMockRepository({ model: modelSource, meta: metaSource, }) {
178
219
  return generateRepository({ model, meta });
179
220
  }
180
221
  exports.generateMockRepository = generateMockRepository;
181
- function generateMainBuildingBlocks({ model, meta, imports, blocks, }) {
182
- if (model.attributes.inMemoryOnly) {
183
- return generateMainBuildingBlocks_InMemoryOnly({ model, meta, imports, blocks });
184
- }
185
- else {
186
- return generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks });
187
- }
188
- }
189
- function generateMainBuildingBlocks_InMemoryOnly({ model, meta, blocks, }) {
190
- const { idField } = model;
222
+ /**
223
+ * Generates the main building blocks of the repository for in-memory model.
224
+ */
225
+ function _generateMainBuildingBlocks_InMemoryOnly({ model, meta, blocks, }) {
191
226
  return {
192
227
  constructorCode: '',
193
228
  initCode: `
194
229
  public async init() {
195
230
  this.data.clear()
196
231
 
197
- ${blocks.uniqueStringFields.clearCode.join('\n')}
198
- ${blocks.default.init.resetCode}
232
+ ${blocks.uniqueStringFieldsBlocks.clearCode.join('\n')}
233
+ ${blocks.defaultValueBlocks.init.resetCode}
199
234
 
200
- ${blocks.index.initCode.join('\n')}
235
+ ${blocks.indexBlocks.initCode.join('\n')}
201
236
 
202
237
  return Promise.resolve()
203
238
  }`,
@@ -210,18 +245,17 @@ function generateMainBuildingBlocks_InMemoryOnly({ model, meta, blocks, }) {
210
245
  public async deleteAll(): Promise<void> {
211
246
  return this.init()
212
247
  }`,
213
- // prettier-ignore
214
248
  createCode: `
215
249
  // Non-mocked version is async - so we keep type-compatible signatures for create() and createWithId()
216
250
  // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars
217
- public async create(item: Omit<${model.typeName}, '${idField.name}'> & Partial<{id: ${idField.unbrandedTypeName}}>): Promise<${model.typeName}> {
251
+ public async create(item: ${blocks.idBlocks.verifyFunctionParameterType}): Promise<${model.typeName}> {
218
252
  const newItem = await Promise.resolve(this.verifyItem(item))
219
253
 
220
254
  this.set(newItem)
221
255
  return newItem
222
256
  }`,
223
257
  createManyCode: `
224
- public async createMany(items: ${blocks.id.verifyFunctionParameterType}[]) {
258
+ public async createMany(items: ${blocks.idBlocks.verifyFunctionParameterType}[]) {
225
259
  const newItems = items.map((item) => this.verifyItem(item))
226
260
 
227
261
  await Promise.resolve()
@@ -243,9 +277,9 @@ function generateMainBuildingBlocks_InMemoryOnly({ model, meta, blocks, }) {
243
277
  }
244
278
 
245
279
 
246
- ${blocks.maxLength.updateCode.join('\n')}
280
+ ${blocks.maxLengthBlocks.updateCode.join('\n')}
247
281
 
248
- ${blocks.uniqueStringFields.updateCode.join('\n')}
282
+ ${blocks.uniqueStringFieldsBlocks.updateCode.join('\n')}
249
283
 
250
284
  const newItem = await Promise.resolve({ ...existingItem, ...item })
251
285
 
@@ -268,6 +302,9 @@ function generateMainBuildingBlocks_InMemoryOnly({ model, meta, blocks, }) {
268
302
  databaseDecoderCode: ``,
269
303
  };
270
304
  }
305
+ /**
306
+ * Generates the methods of the repository for a model that is stored in the database.
307
+ */
271
308
  function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }) {
272
309
  const decoderFunctionName = meta.data.repository.decoderFnName;
273
310
  const { idField } = model;
@@ -281,16 +318,21 @@ function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }
281
318
  items: [`format`, `pluralize`].map(types_1.toTypeName),
282
319
  from: (0, types_1.toFileName)('@pxl/common'),
283
320
  });
321
+ const dbTableName = [model.sourceSchemaName, model.sourceName]
322
+ .filter((s) => s != null)
323
+ .map((part) => `"${part}"`)
324
+ .join('.');
284
325
  return {
285
326
  constructorCode: `constructor(protected db: DbService) {}`,
286
327
  initCode: `
287
328
  public async init() {
288
329
  this.data.clear()
289
330
 
290
- ${blocks.uniqueStringFields.clearCode.join('\n')}
291
- ${blocks.default.init.resetCode}
331
+ ${blocks.uniqueStringFieldsBlocks.clearCode.join('\n')}
332
+
333
+ ${blocks.defaultValueBlocks.init.resetCode}
292
334
 
293
- ${blocks.index.initCode.join('\n')}
335
+ ${blocks.indexBlocks.initCode.join('\n')}
294
336
 
295
337
  const data = await this.db.${meta.data.repository.getMethodFnName}.findMany({})
296
338
 
@@ -298,15 +340,15 @@ function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }
298
340
  const item = this.${decoderFunctionName}(rawItem)
299
341
  this.set(item)
300
342
 
301
- ${blocks.default.init.setCode}
343
+ ${blocks.defaultValueBlocks.init.setCode}
302
344
  }
303
345
 
304
- ${blocks.id.initCode}
346
+ ${blocks.idBlocks.initCode}
305
347
 
306
- ${blocks.default.init.checkCode}
348
+ ${blocks.defaultValueBlocks.init.checkCode}
307
349
 
308
350
  this.logger.log(\`\${format(this.data.size)} \${pluralize('${model.typeName}', this.data.size)} loaded\`)
309
- ${blocks.index.initLogCode.join('\n')}
351
+ ${blocks.indexBlocks.initLogCode.join('\n')}
310
352
  }`,
311
353
  reInitCode: `
312
354
  public async reInit(data: ${model.typeName}[]): Promise<void> {
@@ -316,19 +358,20 @@ function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }
316
358
  this.logger.error(errorMsg)
317
359
  throw new Error(errorMsg)
318
360
  }
361
+
319
362
  await this.db.runOnlyOnTestDb(() => this.db.${meta.data.repository.getMethodFnName}.createMany({ data: data.map((i) => this.toCreateItem(i)) }))
363
+
320
364
  return this.init()
321
365
  }`,
322
366
  deleteAllCode: `
323
367
  public async deleteAll(): Promise<void> {
324
- await this.db.runOnlyOnTestDb(() => this.db.$executeRaw\`DELETE FROM ${model.sourceSchemaName !== undefined ? `"${model.sourceSchemaName}".` : ''}"${model.sourceName}"\`)
325
-
368
+ await this.db.runOnlyOnTestDb(() => this.db.$executeRaw\`DELETE FROM ${dbTableName}\`)
369
+
326
370
  return this.init()
327
371
  }
328
372
  `,
329
- // prettier-ignore
330
373
  createCode: `
331
- public async create(item: Omit<${model.typeName}, '${idField.name}'> & Partial<{ id: ${idField.unbrandedTypeName} }>): Promise<${model.typeName}> {
374
+ public async create(item: ${blocks.idBlocks.verifyFunctionParameterType}): Promise<${model.typeName}> {
332
375
  const newItem = this.${decoderFunctionName}(
333
376
  await this.db.${meta.data.repository.getMethodFnName}.create({
334
377
  data: this.toCreateItem(this.verifyItem(item)),
@@ -339,7 +382,7 @@ function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }
339
382
  return newItem
340
383
  }`,
341
384
  createManyCode: `
342
- public async createMany(items: ${blocks.id.verifyFunctionParameterType}[]) {
385
+ public async createMany(items: ${blocks.idBlocks.verifyFunctionParameterType}[]) {
343
386
  const newItems = items.map((item) => this.verifyItem(item))
344
387
 
345
388
  await this.db.${meta.data.repository.getMethodFnName}.createMany({ data: newItems.map(i => this.toCreateItem(i)) })
@@ -352,16 +395,15 @@ function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }
352
395
  }`,
353
396
  // prettier-ignore
354
397
  updateCode: `
355
- public async update(item: Partial<${model.typeName}> & { id: ${model.brandedIdType}}): Promise<${model.typeName}> {
356
- const existingItem = this.get(item.id)
357
-
398
+ public async update(item: Partial<${model.typeName}> & { ${idField.name}: ${model.brandedIdType} }): Promise<${model.typeName}> {
399
+ const existingItem = this.get(item.${idField.name})
358
400
  if (!existingItem) {
359
401
  throw new Error(\`Could not update ${meta.userFriendlyName} with id \${item.id}. Not found!\`)
360
402
  }
361
403
 
362
- ${blocks.maxLength.updateCode.join('\n')}
404
+ ${blocks.maxLengthBlocks.updateCode.join('\n')}
363
405
 
364
- ${blocks.uniqueStringFields.updateCode.join('\n')}
406
+ ${blocks.uniqueStringFieldsBlocks.updateCode.join('\n')}
365
407
 
366
408
  const newItem = this.${decoderFunctionName}(
367
409
  await this.db.${meta.data.repository.getMethodFnName}.update({
@@ -395,48 +437,42 @@ function generateMainBuildingBlocks_InDatabase({ model, meta, imports, blocks, }
395
437
 
396
438
  this.remove(existingItem)
397
439
  }`,
440
+ // prettier-ignore
398
441
  databaseDecoderCode: `
399
442
  /**
400
443
  * Utility function that converts a given Database object to a TypeScript model instance
401
444
  */
402
- private ${decoderFunctionName}(item: Pick<DbType, ${[...model.fields.values()]
403
- .map((f) => `'${f.sourceName}'`)
404
- .join(' | ')}>): ${model.typeName} {
445
+ private ${decoderFunctionName}(item: Pick<DbType, ${Array.from(model.fields.values()).map((f) => `'${f.sourceName}'`).join(' | ')}>): ${model.typeName} {
405
446
  return ${meta.types.zodDecoderFnName}.parse({
406
- ${[...model.fields.values()].map((f) => `${f.name}: item.${f.sourceName}`).join(',\n')}
447
+ ${Array.from(model.fields.values()).map((f) => `${f.name}: item.${f.sourceName}`).join(',\n')}
407
448
  })
408
449
  }`,
409
450
  };
410
451
  }
411
- function generateBlocks({ model, meta, imports, }) {
412
- return {
413
- id: generateIdBlocks({ model, meta, imports }),
414
- default: generateDefaultBlocks({ model, meta }),
415
- uniqueStringFields: generateUniqueFieldsBlocks({ model, meta }),
416
- maxLength: generateMaxLengthBlocks({ model, meta }),
417
- index: generateIndexBlocks({ model, meta, imports }),
418
- relations: generateRelationsBlocks({ model, meta, imports }),
419
- };
420
- }
421
- function generateIdBlocks({ model, meta, imports, }) {
452
+ function generateIdBlocks({ model, meta }) {
422
453
  const idField = model.idField;
423
454
  if (!idField.isGenerated) {
424
- return generateIdBlocks_NoGeneration({ idField, model, meta });
455
+ return _generateIdBlocks_NoGeneration({ idField, model, meta });
425
456
  }
426
457
  if (idField.schemaType === 'Int') {
427
- return generateIdBlock_Int({ idField, model, meta, imports });
458
+ return _generateIdBlock_Int({ idField, model, meta });
428
459
  }
429
460
  if (idField.schemaType === 'String') {
430
- return generateIdBlock_UUID({ idField, model, meta, imports });
461
+ return _generateIdBlock_UUID({ idField, model, meta });
431
462
  }
432
463
  throw new Error(`Repository block only supports Id generation for number and strings! Found ${idField.schemaType} for model ${model.name} instead!`);
433
464
  }
434
- function generateIdBlocks_NoGeneration({ idField, model, meta, }) {
465
+ /**
466
+ * Generates the id block code chunks for a model that requires an ID field to be manually
467
+ * supplied to the create function.
468
+ */
469
+ function _generateIdBlocks_NoGeneration({ idField, model, meta, }) {
435
470
  return {
436
471
  libraryImports: '',
437
472
  generateNextIdFunctionName: '',
438
473
  initCode: '',
439
474
  verifyFunctionComment: `an error is thrown as field has no default setting in schema.`,
475
+ // TODO: This creates a bug!
440
476
  verifyFunctionParameterType: model.typeName,
441
477
  verifyCode: `
442
478
  if (item.${idField.name} === undefined) {
@@ -446,11 +482,11 @@ function generateIdBlocks_NoGeneration({ idField, model, meta, }) {
446
482
  setCode: '',
447
483
  };
448
484
  }
449
- function generateIdBlock_Int({ idField, model, meta, imports, }) {
450
- imports.addImport({
451
- items: [meta.types.toBrandedIdTypeFnName],
452
- from: meta.types.importPath,
453
- });
485
+ /**
486
+ * Generates the id block code chunks for a model that has an integer id field.
487
+ * Given chunks make sure that the id is unique if provided or generate a new one if not.
488
+ */
489
+ function _generateIdBlock_Int({ idField, model, meta, }) {
454
490
  return {
455
491
  libraryImports: '',
456
492
  generateNextIdFunctionName: `
@@ -465,11 +501,11 @@ function generateIdBlock_Int({ idField, model, meta, imports, }) {
465
501
  setCode: `if (item.id > this.currentMaxId) { this.currentMaxId = item.id }`,
466
502
  };
467
503
  }
468
- function generateIdBlock_UUID({ idField, model, meta, imports, }) {
469
- imports.addImport({
470
- items: [meta.types.toBrandedIdTypeFnName],
471
- from: meta.types.importPath,
472
- });
504
+ /**
505
+ * Generates the id block code chunks for a model that has a UUID id field.
506
+ * It allows you to provide a custom id or generates a new one if not.
507
+ */
508
+ function _generateIdBlock_UUID({ idField, model, meta, }) {
473
509
  return {
474
510
  libraryImports: `import { randomUUID } from 'crypto'`,
475
511
  generateNextIdFunctionName: `
@@ -483,6 +519,9 @@ function generateIdBlock_UUID({ idField, model, meta, imports, }) {
483
519
  setCode: '',
484
520
  };
485
521
  }
522
+ /**
523
+ * Returns the code chunks that define the default value property and its initialization.
524
+ */
486
525
  function generateDefaultBlocks({ model, meta }) {
487
526
  const defaultField = model.defaultField;
488
527
  if (!defaultField) {
@@ -520,6 +559,9 @@ function generateDefaultBlocks({ model, meta }) {
520
559
  `,
521
560
  };
522
561
  }
562
+ /**
563
+ * Generates code chunks that enforce the uniqueness of a given field.
564
+ */
523
565
  function generateUniqueFieldsBlocks({ model }) {
524
566
  const fields = model.fields.filter(fields_1.isUniqueStringField);
525
567
  const result = {
@@ -693,7 +735,7 @@ function generateRelationsBlocks({ model, imports, }) {
693
735
  public ${fieldMeta.getByForeignKeyMethodFnName}(id: ${relationModelMeta.types.brandedIdType}): Map<${model.brandedIdType}, ${model.typeName}> {
694
736
  const result = this.${r.name}Map.get(id)
695
737
  if (!result) return new Map()
696
- return result
738
+ return new Map(result)
697
739
  }
698
740
 
699
741
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/generator",
3
- "version": "0.27.0",
3
+ "version": "0.27.2",
4
4
  "main": "./dist/generator.js",
5
5
  "typings": "./dist/generator.d.ts",
6
6
  "bin": {
@@ -15,8 +15,8 @@
15
15
  },
16
16
  "dependencies": {
17
17
  "@faker-js/faker": "7.6.0",
18
- "@prisma/generator-helper": "4.12.0",
19
- "@prisma/internals": "^4.12.0",
18
+ "@prisma/generator-helper": "5.1.0",
19
+ "@prisma/internals": "^5.1.0",
20
20
  "exceljs": "^4.3.0",
21
21
  "fast-glob": "^3.2.12",
22
22
  "prettier": "^2.8.7",
@@ -25,11 +25,11 @@
25
25
  "@postxl/lock": "0.4.7"
26
26
  },
27
27
  "devDependencies": {
28
- "@prisma/client": "4.12.0",
28
+ "@prisma/client": "5.1.0",
29
29
  "@types/jest": "^29.5.0",
30
30
  "@types/node": "18.15.10",
31
31
  "jest": "29.5.0",
32
- "prisma": "4.12.0",
32
+ "prisma": "5.1.0",
33
33
  "ts-jest": "29.0.5",
34
34
  "ts-node": "10.9.1",
35
35
  "ts-toolbelt": "^9.6.0",
@@ -46,7 +46,7 @@
46
46
  "build": "tsc -p tsconfig.build.json",
47
47
  "prepublish": "tsc -p tsconfig.build.json",
48
48
  "dev": "tsc -p tsconfig.build.json -w",
49
- "test": "./scripts/test.sh",
49
+ "test:generation": "./scripts/test.sh",
50
50
  "test:jest": "jest",
51
51
  "test:watch": "jest --watch",
52
52
  "test:types": "tsc --noEmit"