@postxl/generator 0.68.0 → 0.69.0

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.
@@ -16,11 +16,6 @@ export type ModelAttributes = {
16
16
  * Note: Prisma has it's own schema attribute - but does not expose it in the DMMF.
17
17
  */
18
18
  databaseSchema: string;
19
- /**
20
- * Schema tag: ´@@InMemoryOnly()`
21
- * Whether the model should be stored in the database or only in memory.
22
- */
23
- inMemoryOnly: boolean;
24
19
  /**
25
20
  * Schema tag: ´@@Index()`
26
21
  * Creates an index on the given fields.
@@ -182,10 +182,6 @@ export type SchemaMetaData = {
182
182
  * Location of the module class
183
183
  */
184
184
  moduleLocation: Types.ModuleLocation;
185
- /**
186
- * Path to the file containing the data module class definition.
187
- */
188
- emptyDbCommandFilePath: Types.FilePath;
189
185
  repository: {
190
186
  /**
191
187
  * Path to the file containing the repository type definition.
@@ -218,20 +214,6 @@ export type SchemaMetaData = {
218
214
  */
219
215
  bulkMutationForModel: Types.TypeName;
220
216
  };
221
- mockModule: {
222
- /**
223
- * Path to the file containing the mock data for the database.
224
- */
225
- location: Types.ModuleLocation;
226
- /**
227
- * Name of the mock data module class.
228
- */
229
- name: Types.ClassName;
230
- };
231
- /**
232
- * Name of the data mock type/interface.
233
- */
234
- dataMockDataType: Types.TypeName;
235
217
  dataService: {
236
218
  /**
237
219
  * Path to the file containing data service class definitions.
@@ -350,10 +332,6 @@ export type SchemaMetaData = {
350
332
  * Name of the function that converts a delta to BulkMutations.
351
333
  */
352
334
  deltaToBulkMutations: Types.FunctionName;
353
- /**
354
- * Name of the function that converts mock data to BulkMutations.
355
- */
356
- mockDataToBulkMutations: Types.FunctionName;
357
335
  };
358
336
  /**
359
337
  * Meta data for the import export types file.
@@ -630,10 +608,6 @@ export type SchemaMetaData = {
630
608
  * Meta data for the e2e generators.
631
609
  */
632
610
  e2e: {
633
- /**
634
- * Path to the file containing data mocker class definitions.
635
- */
636
- dataMockerLocation: Types.ModuleLocation;
637
611
  /**
638
612
  * Path to the file containing component test ids for e2e tests.
639
613
  */
@@ -765,26 +739,6 @@ export type ModelMetaData = {
765
739
  */
766
740
  getMethodFnName: Types.FunctionName;
767
741
  };
768
- mockRepository: {
769
- /**
770
- * Path to the file containing the mock repository definition.
771
- */
772
- location: Types.ModuleLocation;
773
- /**
774
- * The name of the class for the in-memory mock repository definition of this model (e.g. MockAggregationRepository).
775
- */
776
- className: Types.ClassName;
777
- };
778
- };
779
- e2e: {
780
- /**
781
- * The path to the file containing stub definitions of this model.
782
- */
783
- stubLocation: Types.ModuleLocation;
784
- /**
785
- * The name of the function that adds missing values to the partially populated model value.
786
- */
787
- stubGenerationFnName: Types.FunctionName;
788
742
  };
789
743
  /**
790
744
  * Properties provided by the `importExport` generators
package/dist/lib/meta.js CHANGED
@@ -118,7 +118,6 @@ function getSchemaMetadata({ config }) {
118
118
  data: {
119
119
  moduleName: Types.toClassName(`DataModule`),
120
120
  moduleLocation: Types.toModuleLocation(`data`, `${config.paths.dataLibPath}data.module`),
121
- emptyDbCommandFilePath: Types.toPath(`${config.paths.dbLibPath}wipe-database.sql`),
122
121
  repository: {
123
122
  typeFilePath: Types.toPath(`${config.paths.dataLibPath}repository.type`),
124
123
  typeName: Types.toTypeName(`Repository`),
@@ -138,14 +137,8 @@ function getSchemaMetadata({ config }) {
138
137
  },
139
138
  stubIndexFilePath: Types.toPath(`${config.paths.dataLibPath}stubs/index`),
140
139
  testDataServiceFilePath: Types.toPath(`${config.paths.e2eLibPath}test-data.service`),
141
- mockModule: {
142
- location: Types.toModuleLocation(`data`, `${config.paths.dataLibPath}data.mock.module`),
143
- name: Types.toClassName(`DataMockModule`),
144
- },
145
- dataMockDataType: Types.toTypeName(`MockData`),
146
140
  },
147
141
  e2e: {
148
- dataMockerLocation: Types.toModuleLocation(`e2e`, `${config.paths.playwrightPath}support/data-mocker.class`),
149
142
  testIdsFilePath: Types.toPath(`${config.paths.playwrightPath}support/model-test-ids`),
150
143
  },
151
144
  importExport: {
@@ -174,7 +167,6 @@ function getSchemaMetadata({ config }) {
174
167
  location: Types.toModuleLocation(`import-export`, `${config.paths.importExportPath}convert-import.functions`),
175
168
  importedDataToBulkMutations: Types.toFunctionName(`importToBulkMutations`),
176
169
  deltaToBulkMutations: Types.toFunctionName(`deltaToBulkMutations`),
177
- mockDataToBulkMutations: Types.toFunctionName(`mockDataToBulkMutations`),
178
170
  },
179
171
  types: {
180
172
  location: Types.toModuleLocation(`import-export`, `${config.paths.importExportPath}types`),
@@ -284,20 +276,12 @@ function getModelMetadata({ model }) {
284
276
  decoderFnName: Types.toFunctionName(`to${PascalCase}`),
285
277
  getMethodFnName: Types.toFunctionName(`${camelCase}`),
286
278
  },
287
- mockRepository: {
288
- location: Types.toModuleLocation(`data`, `${config.paths.dataLibPath}repositories/mock/${camelCase}.mock.repository`),
289
- className: Types.toClassName(`Mock${PascalCase}Repository`),
290
- },
291
279
  stubLocation: Types.toModuleLocation(`data`, `${config.paths.dataLibPath}stubs/${camelCase}.stub`),
292
280
  stubGenerationFnName: Types.toFunctionName(`stub${PascalCase}`),
293
281
  defaultStubConstantName: Types.toVariableName(`${camelCase}DefaultStub`),
294
282
  dataServiceName: Types.toVariableName(`${uncapitalizedPlural}`),
295
283
  dataServiceIdName: Types.toVariableName(`${uncapitalized}`),
296
284
  },
297
- e2e: {
298
- stubGenerationFnName: Types.toFunctionName(`stub${PascalCase}`),
299
- stubLocation: Types.toModuleLocation(`e2e`, `${config.paths.playwrightPath}support/stubs/${camelCase}.stub`),
300
- },
301
285
  importExport: {
302
286
  exportDataPropertyName: Types.toVariableName(`${capitalizedPlural}`),
303
287
  exportDataFullPropertyName: Types.toVariableName(`${uncapitalizedPlural}`),
@@ -71,7 +71,6 @@ function getModelAttributes(model) {
71
71
  const decoder = zod_1.default
72
72
  .object({
73
73
  ignore: blankStringBooleanDecoder,
74
- inMemoryOnly: blankStringBooleanDecoder,
75
74
  description: zod_1.default.string().optional(),
76
75
  schema: zod_1.default.string({
77
76
  required_error: `The PostXL attribute ${(0, logger_1.highlight)('`///@@Schema`')} attribute must be provided (in addition to Prisma's @@schema attribute)!`,
@@ -85,7 +84,6 @@ function getModelAttributes(model) {
85
84
  })
86
85
  .transform((obj) => ({
87
86
  ignore: obj.ignore,
88
- inMemoryOnly: obj.inMemoryOnly,
89
87
  description: obj.description,
90
88
  databaseSchema: obj.schema,
91
89
  index: obj.index,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/generator",
3
- "version": "0.68.0",
3
+ "version": "0.69.0",
4
4
  "main": "./dist/generator.js",
5
5
  "typings": "./dist/generator.d.ts",
6
6
  "bin": {
@@ -1,9 +0,0 @@
1
- import { SchemaMetaData } from '../../lib/meta';
2
- import { Model } from '../../lib/schema/schema';
3
- /**
4
- * Generates a mocking class
5
- */
6
- export declare function generateDataMockModule({ models, meta }: {
7
- models: Model[];
8
- meta: SchemaMetaData;
9
- }): string;
@@ -1,64 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateDataMockModule = void 0;
4
- const imports_1 = require("../../lib/imports");
5
- const meta_1 = require("../../lib/meta");
6
- /**
7
- * Generates a mocking class
8
- */
9
- function generateDataMockModule({ models, meta }) {
10
- const mm = models.map((model) => ({ model, meta: (0, meta_1.getModelMetadata)({ model }) }));
11
- const imports = imports_1.ImportsGenerator.from(meta.data.mockModule.location.path).addImports({
12
- [meta.data.moduleLocation.path]: [meta.data.moduleName],
13
- [meta.data.dataService.location.path]: [meta.data.dataService.class],
14
- [meta.backendModules.db.moduleLocation.import]: [meta.backendModules.db.moduleName],
15
- // we need to import the file directly instead via the normal index file as this would cause a circular dependency else
16
- [meta.actions.execution.mockLocation.import]: [meta.actions.execution.mock],
17
- });
18
- for (const { model, meta } of mm) {
19
- imports.addTypeImport({ items: [model.typeName], from: meta.types.importPath });
20
- imports.addImport({ items: [meta.data.repository.className], from: meta.data.repository.location.path });
21
- imports.addImport({ items: [meta.data.mockRepository.className], from: meta.data.mockRepository.location.path });
22
- }
23
- const providers = mm
24
- .map(({ meta }) => `{
25
- provide: ${meta.data.repository.className},
26
- useFactory: async () => {
27
- const repository = new ${meta.data.mockRepository.className}()
28
- if (!!seed && !!seed.${meta.seed.constantName}) {
29
- await repository.reInit({items: seed.${meta.seed.constantName}, execution })
30
- }
31
- return repository
32
- }
33
- }`)
34
- .join(', ');
35
- return /* ts */ `
36
- import { DynamicModule } from '@nestjs/common'
37
-
38
- ${imports.generate()}
39
-
40
- export class ${meta.data.mockModule.name} {
41
- static mock(seed?: MockData): DynamicModule {
42
- const execution = new MockActionExecution()
43
-
44
- const providers = [
45
- DataService,
46
- ${providers}
47
- ]
48
-
49
- return {
50
- module: ${meta.data.moduleName},
51
- imports: [DatabaseModule.provideMock()],
52
- providers,
53
- exports: providers,
54
- global: true,
55
- }
56
- }
57
- }
58
-
59
- export interface ${meta.data.dataMockDataType} {
60
- ${mm.map(({ model, meta }) => `${meta.data.mockDataPropertyName}?: ${model.typeName}[]`).join('\n')}
61
- }
62
- `;
63
- }
64
- exports.generateDataMockModule = generateDataMockModule;
@@ -1,9 +0,0 @@
1
- import { SchemaMetaData } from '../../lib/meta';
2
- import { Model } from '../../lib/schema/schema';
3
- /**
4
- * Generates a generic data mocker class.
5
- */
6
- export declare function generateDataMocker({ models, meta: schemaMeta }: {
7
- models: Model[];
8
- meta: SchemaMetaData;
9
- }): string;
@@ -1,88 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateDataMocker = void 0;
4
- const imports_1 = require("../../lib/imports");
5
- const meta_1 = require("../../lib/meta");
6
- const schema_1 = require("../../lib/schema/schema");
7
- const types_1 = require("../../lib/schema/types");
8
- /**
9
- * Generates a generic data mocker class.
10
- */
11
- function generateDataMocker({ models, meta: schemaMeta }) {
12
- const modelMetas = models.map((model) => ({ model, meta: (0, meta_1.getModelMetadata)({ model }) }));
13
- const imports = imports_1.ImportsGenerator.from(schemaMeta.e2e.dataMockerLocation.path);
14
- for (const { model, meta } of modelMetas) {
15
- imports.addImports({
16
- [meta.types.importPath]: [(0, types_1.toAnnotatedTypeName)(model.typeName)],
17
- [meta.e2e.stubLocation.path]: [meta.e2e.stubGenerationFnName],
18
- });
19
- }
20
- const publicVariables = modelMetas
21
- .map(({ model, meta }) => `public ${meta.data.dataServiceName}: ${model.typeName}[] = []`)
22
- .join('\n');
23
- const privateIds = modelMetas
24
- .map(({ model, meta }) => `private ${meta.data.dataServiceIdName}Ids = new IdTracker<${model.typeName}>()`)
25
- .join('\n');
26
- const addDataFunctions = modelMetas.map(({ model, meta }) => generateAddDataFunction(model, meta)).join('\n');
27
- return `
28
- /* eslint-disable @typescript-eslint/no-unused-vars */
29
- import type { MockData } from '@backend/data/data.mock.module'
30
-
31
- ${imports.generate()}
32
-
33
- import { IdTracker } from './id-tracker.class'
34
-
35
-
36
- export class DataMocker implements MockData {
37
- ${publicVariables}
38
-
39
- ${privateIds}
40
-
41
- ${addDataFunctions}
42
- }
43
- `;
44
- }
45
- exports.generateDataMocker = generateDataMocker;
46
- function generateAddDataFunction(model, meta) {
47
- const { fields, idField } = model;
48
- const relations = fields
49
- .filter(schema_1.isFieldRelation)
50
- .map((field) => (Object.assign(Object.assign({}, field), { meta: (0, meta_1.getModelMetadata)({ model: field.relationToModel }), fieldMeta: (0, meta_1.getFieldMetadata)({ field }), model: field.relationToModel })))
51
- .map((r) => {
52
- if (r.isRequired) {
53
- return `
54
- if (_item.${r.name}) {
55
- if (this.${r.meta.data.dataServiceName}.findIndex((x) => x.id === _item.${r.name}) === -1) {
56
- this.add${r.model.typeName}({ id: _item.${r.name} })
57
- }
58
- } else {
59
- if (this.${r.meta.data.dataServiceName}.length === 0) {
60
- this.add${r.model.typeName}()
61
- }
62
- _item.${r.name} = this.${r.meta.data.dataServiceName}[0].id
63
- }
64
- `;
65
- }
66
- return `
67
- if (_item.${r.name}) {
68
- if (this.${r.meta.data.dataServiceName}.findIndex((x) => x.id === _item.${r.name}) === -1) {
69
- this.add${r.model.typeName}({ id: _item.${r.name} })
70
- }
71
- }
72
- `;
73
- });
74
- // TODO: Move the publicly accessible function's name to the metadata definition!
75
- return /* ts */ `
76
- public add${model.typeName}(
77
- item?: Partial<Omit<${model.typeName}, '${idField.name}'> & { ${idField.name}: ${idField.unbrandedTypeName} }>
78
- ): DataMocker {
79
- const _stub = stub${model.typeName}(item ?? {})
80
- const _item = this.${meta.data.dataServiceIdName}Ids.ensureId(_stub)
81
-
82
- this.${meta.data.dataServiceName}.push(_item)
83
-
84
- ${relations.join('\n')}
85
-
86
- return this
87
- }`;
88
- }
@@ -1,11 +0,0 @@
1
- import { SchemaMetaData } from '../../lib/meta';
2
- import { Model } from '../../lib/schema/schema';
3
- /**
4
- * Generates a const that contains the SQL to delete all data from the E2E database.
5
- *
6
- * This is used in e2e tests to empty the database before each test.
7
- */
8
- export declare function generateEmptyDatabaseCommand({ models }: {
9
- models: Model[];
10
- meta: SchemaMetaData;
11
- }): string;
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateEmptyDatabaseCommand = void 0;
4
- /**
5
- * Generates a const that contains the SQL to delete all data from the E2E database.
6
- *
7
- * This is used in e2e tests to empty the database before each test.
8
- */
9
- function generateEmptyDatabaseCommand({ models }) {
10
- const modelTables = models.map((model) => `${model.sourceSchemaName !== undefined ? `"${model.sourceSchemaName}".` : ''}"${model.sourceName}"`);
11
- // We determine the schema used for all system tables by looking at the User model's schema.
12
- const userModel = models.find((model) => model.name === 'User');
13
- if (!userModel) {
14
- throw new Error('Model definition for "User" could not be found - hence schema for system table cannot be derived!');
15
- }
16
- const configSchema = userModel.sourceSchemaName !== undefined ? `"${userModel.sourceSchemaName}".` : '';
17
- const systemTables = ['Action', 'Mutation'].map((table) => `${configSchema}"${table}"`);
18
- const configTableName = `${configSchema}"Config"`;
19
- return /** ts */ `
20
- /**
21
- * SQL instruction to delete all data from the E2E database. Should only be used internally by the DbService!
22
- */
23
- export const wipeDatabaseCommand = \`
24
- DO $$
25
- BEGIN
26
- IF EXISTS (SELECT 1 FROM ${configTableName} WHERE "isTest" = TRUE) THEN
27
- TRUNCATE TABLE
28
- ${[...systemTables, ...modelTables].join(',\n ')};
29
- END IF;
30
- END
31
- $$;\`
32
- `;
33
- }
34
- exports.generateEmptyDatabaseCommand = generateEmptyDatabaseCommand;
@@ -1,9 +0,0 @@
1
- import { SchemaMetaData } from '../../lib/meta';
2
- import { Model } from '../../lib/schema/schema';
3
- /**
4
- * Generates the TestDataService class.
5
- */
6
- export declare function generateTestDataService({ models, meta: schemaMeta, }: {
7
- models: Model[];
8
- meta: SchemaMetaData;
9
- }): string;
@@ -1,84 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateTestDataService = void 0;
4
- const imports_1 = require("../../lib/imports");
5
- const meta_1 = require("../../lib/meta");
6
- const types_1 = require("../../lib/schema/types");
7
- /**
8
- * Generates the TestDataService class.
9
- */
10
- function generateTestDataService({ models, meta: schemaMeta, }) {
11
- const imports = imports_1.ImportsGenerator.from(schemaMeta.data.testDataServiceFilePath);
12
- imports.addImports({
13
- [schemaMeta.actions.execution.classLocation.import]: [(0, types_1.toClassName)('ActionExecutionFactory')],
14
- [schemaMeta.data.dataService.location.import]: [schemaMeta.data.dataService.class],
15
- [schemaMeta.backendModules.db.databaseService.location.import]: [schemaMeta.backendModules.db.databaseService.name],
16
- [schemaMeta.data.mockModule.location.import]: [(0, types_1.toAnnotatedTypeName)(schemaMeta.data.dataMockDataType)],
17
- [schemaMeta.importExport.converterFunctions.location.import]: [
18
- schemaMeta.importExport.converterFunctions.mockDataToBulkMutations,
19
- ],
20
- });
21
- const reInitCalls = [];
22
- const modelMetas = models.map((model) => ({ model, meta: (0, meta_1.getModelMetadata)({ model }) }));
23
- for (const { model, meta } of modelMetas) {
24
- if (model.defaultField) {
25
- imports.addImport({ items: [meta.data.stubGenerationFnName], from: meta.data.stubLocation.import });
26
- const stubDefault = `${meta.data.stubGenerationFnName}({ ${model.defaultField.name}: true })`;
27
- reInitCalls.push(`await this.dataService.${meta.data.dataServiceName}.reInit({ items: mockData.${meta.seed.constantName}?.create ?? [${stubDefault}], execution: actionExecution })`);
28
- }
29
- else {
30
- reInitCalls.push(`await this.dataService.${meta.data.dataServiceName}.reInit({ items: mockData.${meta.seed.constantName}?.create ?? [], execution: actionExecution })`);
31
- }
32
- }
33
- return /* ts */ `
34
- import { Injectable, Logger } from '@nestjs/common'
35
-
36
- ${imports.generate()}
37
-
38
- @Injectable()
39
- export class TestDataService {
40
- private logger = new Logger(TestDataService.name)
41
-
42
- constructor(
43
- private readonly databaseService: DatabaseService,
44
- private readonly dataService: ${schemaMeta.data.dataService.class},
45
- private readonly actionExecutionFactory: ActionExecutionFactory,
46
- ) {}
47
-
48
- public async resetTestData(data: MockData) {
49
- this.logger.log('💥 Emptying test data')
50
- await this.databaseService.WIPE_ENTIRE_DATABASE()
51
-
52
- // We need to init the user repository first so the root user is created
53
- this.logger.log('✍ Setting test data')
54
- await this.dataService.users.init()
55
-
56
- this.logger.log('✍ Setting test data')
57
-
58
- const mockData = ${schemaMeta.importExport.converterFunctions.mockDataToBulkMutations}(data)
59
-
60
- const actionExecution = await this.actionExecutionFactory.create({
61
- action: {
62
- scope: 'seed',
63
- type: 'data',
64
- name: 'E2E',
65
- order: 0,
66
- payload: []
67
- },
68
- databaseService: this.databaseService,
69
- user: this.dataService.users.rootUser,
70
- })
71
-
72
- try {
73
- ${reInitCalls.join('\n')}
74
-
75
- await actionExecution.success()
76
- this.logger.log('✅ Reset test data')
77
- } catch (e) {
78
- await actionExecution.error(e)
79
- throw e
80
- }
81
- }
82
- }`;
83
- }
84
- exports.generateTestDataService = generateTestDataService;