@postxl/generator 0.51.0 → 0.52.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
@@ -84,6 +84,7 @@ const parse_1 = require("./prisma/parse");
84
84
  const CONFIG_SCHEMA = zod_1.z
85
85
  .object({
86
86
  pathToDataLib: zod_1.z.string().optional(),
87
+ pathToDbLib: zod_1.z.string().optional(),
87
88
  pathToCypress: zod_1.z.string().optional(),
88
89
  pathToE2ELib: zod_1.z.string().optional(),
89
90
  pathToImportExport: zod_1.z.string().optional(),
@@ -108,6 +109,7 @@ const CONFIG_SCHEMA = zod_1.z
108
109
  return {
109
110
  paths: {
110
111
  dataLibPath: (0, types_1.toPath)(s.pathToDataLib || './backend/libs/data/src/'),
112
+ dbLibPath: (0, types_1.toPath)(s.pathToDbLib || './backend/libs/db/src/'),
111
113
  cypressPath: (0, types_1.toPath)(s.pathToCypress || './e2e/cypress/'),
112
114
  e2eLibPath: (0, types_1.toPath)(s.pathToE2ELib || './backend/libs/e2e/src/'),
113
115
  importExportPath: (0, types_1.toPath)(s.pathToImportExport || './backend/libs/import-export/src/'),
@@ -203,6 +205,7 @@ function generate({ models, enums, config, prismaClientPath, logger, }) {
203
205
  // Data
204
206
  generated.write(`/${meta.data.dataMockModuleFilePath}.ts`, (0, datamock_module_generator_1.generateDataMockModule)({ models, meta }));
205
207
  generated.write(`/${meta.data.dataModuleFilePath}.ts`, (0, datamodule_generator_1.generateDataModule)({ models, meta }));
208
+ generated.write(`/${meta.data.emptyDbCommandFilePath}.ts`, (0, emptydatabasemigration_generator_1.generateEmptyDatabaseCommand)({ models, meta }));
206
209
  generated.write(`/${meta.data.dataService.filePath}.ts`, (0, dataservice_generator_1.generateDataService)({ models, meta }));
207
210
  generated.write(`/${meta.data.testDataServiceFilePath}.ts`, (0, testdata_service_generator_1.generateTestDataService)({ models, meta }));
208
211
  generated.write(`/${meta.e2e.dataMocker.filePath}.ts`, (0, datamocker_generator_1.generateDataMocker)({ models, meta }));
@@ -212,12 +215,6 @@ function generate({ models, enums, config, prismaClientPath, logger, }) {
212
215
  generated.write(`/${meta.data.repository.indexFilePath}.ts`, (0, repositories_generator_1.generateRepositoriesIndex)({ models, meta }));
213
216
  generated.write(`/${meta.data.stubIndexFilePath}.ts`, (0, stubs_generator_1.generateStubsIndex)({ models, meta }));
214
217
  generated.write(`/${meta.data.types.filePath}.ts`, (0, data_types_generator_1.generateDataTypes)({ models, meta }));
215
- // We only generate the empty database migration if the migration folder already has an existing migration
216
- // Else we would generate a migration that deletes from tables that have not yet been created in the database
217
- // We include this check here as the template does not come with any migration - hence this migration should also not be generated
218
- if ((0, emptydatabasemigration_generator_1.prismaMigrationExists)(meta)) {
219
- generated.write((0, emptydatabasemigration_generator_1.deriveEmptyDatabaseMigrationFilePath)(meta), (0, emptydatabasemigration_generator_1.generateEmptyDatabaseStoredProcedure)({ models, meta }));
220
- }
221
218
  // Import-Export
222
219
  generated.write(`/${meta.importExport.types.filePath}.ts`, (0, importexport_types_generator_1.generateImportExportTypes)({ models, meta }));
223
220
  generated.write(`/${meta.importExport.exporterClass.filePath}.ts`, (0, importexport_exporter_class_generator_1.generateImportExportExporterClass)({ models, meta }));
@@ -1,22 +1,11 @@
1
1
  import { SchemaMetaData } from '../../lib/meta';
2
2
  import { Model } from '../../lib/schema/schema';
3
3
  /**
4
- * Generates a the Prisma migration to create the `emptyDatabase` stored procedure.
4
+ * Generates a const that contains the SQL to delete all data from the E2E database.
5
5
  *
6
- * The routine is used in e2e tests to empty the database before each test.
6
+ * This is used in e2e tests to empty the database before each test.
7
7
  */
8
- export declare function generateEmptyDatabaseStoredProcedure({ models }: {
8
+ export declare function generateEmptyDatabaseCommand({ models }: {
9
9
  models: Model[];
10
10
  meta: SchemaMetaData;
11
11
  }): string;
12
- /**
13
- * Generates a the full file path for the Prisma migration to create the `emptyDatabase` stored procedure.
14
- *
15
- * This is done by finding the first migration in the migrations folder and using its timestamp + 1.
16
- * In case no migration is found, an error is shown!
17
- */
18
- export declare function deriveEmptyDatabaseMigrationFilePath(meta: SchemaMetaData): string;
19
- /**
20
- * Checks if any Prisma migration exists.
21
- */
22
- export declare function prismaMigrationExists(meta: SchemaMetaData): boolean;
@@ -1,74 +1,34 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.prismaMigrationExists = exports.deriveEmptyDatabaseMigrationFilePath = exports.generateEmptyDatabaseStoredProcedure = void 0;
7
- const fs_1 = __importDefault(require("fs"));
3
+ exports.generateEmptyDatabaseCommand = void 0;
8
4
  /**
9
- * Generates a the Prisma migration to create the `emptyDatabase` stored procedure.
5
+ * Generates a const that contains the SQL to delete all data from the E2E database.
10
6
  *
11
- * The routine is used in e2e tests to empty the database before each test.
7
+ * This is used in e2e tests to empty the database before each test.
12
8
  */
13
- function generateEmptyDatabaseStoredProcedure({ models }) {
14
- const modelTables = models
15
- .map((model) => `\t${model.sourceSchemaName !== undefined ? `"${model.sourceSchemaName}".` : ''}"${model.sourceName}"`);
9
+ function generateEmptyDatabaseCommand({ models }) {
10
+ const modelTables = models.map((model) => `${model.sourceSchemaName !== undefined ? `"${model.sourceSchemaName}".` : ''}"${model.sourceName}"`);
16
11
  // We determine the schema used for all system tables by looking at the User model's schema.
17
12
  const userModel = models.find((model) => model.name === 'User');
18
13
  if (!userModel) {
19
14
  throw new Error('Model definition for "User" could not be found - hence schema for system table cannot be derived!');
20
15
  }
21
16
  const configSchema = userModel.sourceSchemaName !== undefined ? `"${userModel.sourceSchemaName}".` : '';
22
- const systemTables = ["Action", "Mutation"].map((table) => `\t${configSchema}"${table}"`);
17
+ const systemTables = ['Action', 'Mutation'].map((table) => `${configSchema}"${table}"`);
23
18
  const configTableName = `${configSchema}"Config"`;
24
- return `
25
- CREATE OR REPLACE PROCEDURE "emptyDatabase"() AS $BODY$ BEGIN IF EXISTS (
26
- SELECT
27
- FROM ${configTableName}
28
- WHERE NOT "isTest"
29
- ) THEN RETURN;
30
- END IF;
31
- TRUNCATE TABLE
32
- ${[...systemTables, ...modelTables].join(',\n')};
33
-
34
- END;
35
- $BODY$ LANGUAGE plpgsql;
36
- `;
37
- }
38
- exports.generateEmptyDatabaseStoredProcedure = generateEmptyDatabaseStoredProcedure;
39
- /**
40
- * Generates a the full file path for the Prisma migration to create the `emptyDatabase` stored procedure.
41
- *
42
- * This is done by finding the first migration in the migrations folder and using its timestamp + 1.
43
- * In case no migration is found, an error is shown!
44
- */
45
- function deriveEmptyDatabaseMigrationFilePath(meta) {
46
- const firstMigration = getFirstPrismaMigration(meta);
47
- if (firstMigration === undefined) {
48
- throw new Error(`No Prisma migration found in ${meta.prismaMigrationsPath}! Please run "prisma migrate dev" first.`);
49
- }
50
- const existingTimestamp = firstMigration.split('_')[0];
51
- const nextTimestamp = (Number.parseInt(existingTimestamp) + 1).toString();
52
- return `/${meta.prismaMigrationsPath}/${nextTimestamp}_emptyDatabase/migration.sql`;
53
- }
54
- exports.deriveEmptyDatabaseMigrationFilePath = deriveEmptyDatabaseMigrationFilePath;
55
- /**
56
- * Checks if any Prisma migration exists.
57
- */
58
- function prismaMigrationExists(meta) {
59
- const firstMigration = getFirstPrismaMigration(meta);
60
- return firstMigration !== undefined;
61
- }
62
- exports.prismaMigrationExists = prismaMigrationExists;
63
- /**
64
- * Returns the first migration in the migrations folder if it exists.
19
+ return /** ts */ `
20
+ /**
21
+ * SQL instruction to delete all data from the E2E database. Should only be used internally by the DbService!
65
22
  */
66
- function getFirstPrismaMigration(meta) {
67
- const folder = meta.prismaMigrationsPath;
68
- try {
69
- return fs_1.default.readdirSync(folder).find((f) => fs_1.default.statSync(`${folder}/${f}`).isDirectory());
70
- }
71
- catch (err) {
72
- return undefined;
73
- }
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
+ `;
74
33
  }
34
+ exports.generateEmptyDatabaseCommand = generateEmptyDatabaseCommand;
@@ -47,11 +47,14 @@ export class TestDataService {
47
47
  ) {}
48
48
 
49
49
  public async resetTestData(data: MockData) {
50
+ this.logger.log('💥 Emptying test data')
50
51
  await this.db.WIPE_ENTIRE_DATABASE()
51
52
 
52
53
  // We need to init the user repository first so the root user is created
53
54
  await this.dataService.users.init()
54
55
 
56
+ this.logger.log('✍ Setting test data')
57
+
55
58
  const mockData = ${schemaMeta.importExport.converterFunctions.mockDataToBulkMutations}(data)
56
59
  const action = createActionSeedData({ name: 'E2E', order: 0, data: [] })
57
60
  const actionExecution = await this.actionExecutionFactory.create({
@@ -63,7 +66,7 @@ export class TestDataService {
63
66
  ${reInitCalls.join('\n')}
64
67
 
65
68
  await actionExecution.success()
66
- this.logger.log(\`✅ Reset test data\`)
69
+ this.logger.log('✅ Reset test data')
67
70
  } catch (e) {
68
71
  await actionExecution.error(e)
69
72
  throw e
@@ -134,6 +134,10 @@ export type SchemaMetaData = {
134
134
  * Path to the file containing the data module class definition.
135
135
  */
136
136
  dataModuleFilePath: Types.FilePath;
137
+ /**
138
+ * Path to the file containing the data module class definition.
139
+ */
140
+ emptyDbCommandFilePath: Types.FilePath;
137
141
  /**
138
142
  * Path to the file containing the mock data for the database.
139
143
  */
package/dist/lib/meta.js CHANGED
@@ -119,6 +119,7 @@ function getSchemaMetadata({ config }) {
119
119
  importPath: Types.toBackendModulePath(`@backend/data`),
120
120
  dataModuleFilePath: Types.toPath(`${config.paths.dataLibPath}data.module`),
121
121
  dataMockModuleFilePath: Types.toPath(`${config.paths.dataLibPath}data.mock.module`),
122
+ emptyDbCommandFilePath: Types.toPath(`${config.paths.dbLibPath}wipe-database.sql`),
122
123
  repository: {
123
124
  typeFilePath: Types.toPath(`${config.paths.dataLibPath}repository.type`),
124
125
  typeName: Types.toTypeName(`Repository`),
@@ -12,14 +12,14 @@ export type SchemaConfig = {
12
12
  * Path to the directory containing actions.
13
13
  *
14
14
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
15
- * may reference actions using `@project/actions` import.
15
+ * may reference actions using `@backend/actions` import.
16
16
  */
17
17
  actionsPath: Types.FilePath;
18
18
  /**
19
19
  * Path to the directory containing business logic.
20
20
  *
21
21
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
22
- * may reference mock data using `@project/business-logic` import.
22
+ * may reference mock data using `@backend/business-logic` import.
23
23
  */
24
24
  businessLogicPath: Types.FilePath;
25
25
  /**
@@ -34,14 +34,21 @@ export type SchemaConfig = {
34
34
  * Path to the directory containing data library definitions.
35
35
  *
36
36
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
37
- * may reference data library using `@project/data` import.
37
+ * may reference data library using `@backend/data` import.
38
38
  */
39
39
  dataLibPath: Types.FilePath;
40
+ /**
41
+ * Path to the directory containing db library definitions.
42
+ *
43
+ * NOTE: Metadata assumes that project is set up so that certain parts of the code
44
+ * may reference data library using `@backend/db` import.
45
+ */
46
+ dbLibPath: Types.FilePath;
40
47
  /**
41
48
  * Path to the directory containing import-export module.
42
49
  *
43
50
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
44
- * may reference import-export using `@project/import-export` import.
51
+ * may reference import-export using `@backend/import-export` import.
45
52
  */
46
53
  importExportPath: Types.FilePath;
47
54
  /**
@@ -52,28 +59,28 @@ export type SchemaConfig = {
52
59
  * Path to the directory containing model type definitions.
53
60
  *
54
61
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
55
- * may reference type definitions using `@project/types` import.
62
+ * may reference type definitions using `@backend/types` import.
56
63
  */
57
64
  modelTypeDefinitionsPath: Types.FilePath;
58
65
  /**
59
66
  * Path to the directory containing React components.
60
67
  *
61
68
  * NOTE: Metadata assumes that the project is set up so that React components
62
- * may be referenced using `@project/react` import.
69
+ * may be referenced using `@backend/react` import.
63
70
  */
64
71
  reactFolderPath: Types.FilePath;
65
72
  /**
66
73
  * Path to the directory containing seed module.
67
74
  *
68
75
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
69
- * may reference mock data using `@project/seed` import.
76
+ * may reference mock data using `@backend/seed` import.
70
77
  */
71
78
  seedLibPath: Types.FilePath;
72
79
  /**
73
80
  * Path to the directory containing mock data samples.
74
81
  *
75
82
  * NOTE: Metadata assumes that project is set up so that certain parts of the code
76
- * may reference mock data using `@project/seed-data` import.
83
+ * may reference mock data using `@backend/seed-data` import.
77
84
  */
78
85
  seedDataPath: Types.FilePath;
79
86
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/generator",
3
- "version": "0.51.0",
3
+ "version": "0.52.1",
4
4
  "main": "./dist/generator.js",
5
5
  "typings": "./dist/generator.d.ts",
6
6
  "bin": {