@anarchitects/nx-typeorm 0.0.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.
Files changed (49) hide show
  1. package/README.md +84 -0
  2. package/dist/executors/ensure-schema/executor.d.ts +10 -0
  3. package/dist/executors/ensure-schema/executor.d.ts.map +1 -0
  4. package/dist/executors/ensure-schema/executor.js +77 -0
  5. package/dist/executors/ensure-schema/schema.json +23 -0
  6. package/dist/executors/generate/executor.d.ts +12 -0
  7. package/dist/executors/generate/executor.d.ts.map +1 -0
  8. package/dist/executors/generate/executor.js +39 -0
  9. package/dist/executors/generate/schema.json +40 -0
  10. package/dist/executors/revert/executor.d.ts +10 -0
  11. package/dist/executors/revert/executor.d.ts.map +1 -0
  12. package/dist/executors/revert/executor.js +22 -0
  13. package/dist/executors/revert/schema.json +27 -0
  14. package/dist/executors/run/executor.d.ts +11 -0
  15. package/dist/executors/run/executor.d.ts.map +1 -0
  16. package/dist/executors/run/executor.js +25 -0
  17. package/dist/executors/run/schema.json +31 -0
  18. package/dist/executors/seed/executor.d.ts +12 -0
  19. package/dist/executors/seed/executor.d.ts.map +1 -0
  20. package/dist/executors/seed/executor.js +44 -0
  21. package/dist/executors/seed/schema.json +31 -0
  22. package/dist/executors/shared.d.ts +25 -0
  23. package/dist/executors/shared.d.ts.map +1 -0
  24. package/dist/executors/shared.js +71 -0
  25. package/dist/generators/bootstrap/files/app/docker-compose.yml__tmpl__ +19 -0
  26. package/dist/generators/bootstrap/files/app/env.example__tmpl__ +1 -0
  27. package/dist/generators/bootstrap/files/app/src/typeorm.datasource.ts__tmpl__ +15 -0
  28. package/dist/generators/bootstrap/files/app/tools/typeorm/datasource.migrations.ts__tmpl__ +9 -0
  29. package/dist/generators/bootstrap/files/app/tools/typeorm/datasource.runtime.ts__tmpl__ +9 -0
  30. package/dist/generators/bootstrap/files/app/tools/typeorm/migrations/.gitkeep__tmpl__ +0 -0
  31. package/dist/generators/bootstrap/files/app/tools/typeorm/seeds/index.ts__tmpl__ +3 -0
  32. package/dist/generators/bootstrap/files/lib/project.json.partial__tmpl__ +9 -0
  33. package/dist/generators/bootstrap/files/lib/src/infrastructure-persistence/migrations/1700000000000_init_schema.ts__tmpl__ +12 -0
  34. package/dist/generators/bootstrap/files/lib/src/infrastructure-persistence/schema.ts__tmpl__ +1 -0
  35. package/dist/generators/bootstrap/generator.d.ts +12 -0
  36. package/dist/generators/bootstrap/generator.d.ts.map +1 -0
  37. package/dist/generators/bootstrap/generator.js +167 -0
  38. package/dist/generators/bootstrap/schema.json +37 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +6 -0
  42. package/dist/index.json +30 -0
  43. package/dist/plugins/typeorm.d.ts +7 -0
  44. package/dist/plugins/typeorm.d.ts.map +1 -0
  45. package/dist/plugins/typeorm.js +161 -0
  46. package/dist/utils/spawn.d.ts +6 -0
  47. package/dist/utils/spawn.d.ts.map +1 -0
  48. package/dist/utils/spawn.js +11 -0
  49. package/package.json +81 -0
package/README.md ADDED
@@ -0,0 +1,84 @@
1
+ # @anarchitects/nx-typeorm
2
+
3
+ Nx plugin that gives Rails-like ergonomics for TypeORM projects. It wires common
4
+ TypeORM workflows into the Nx task system so you can run migrations, seeds, and
5
+ bootstrap new projects without leaving `nx`.
6
+
7
+ ## Purpose
8
+
9
+ - Detect TypeORM-enabled projects and infer common Nx targets (run, revert,
10
+ seed, ensure-schema).
11
+ - Provide thin executors that proxy TypeORM CLI commands through the active
12
+ package manager.
13
+ - Scaffold applications or libraries with ready-to-use TypeORM wiring, seeds,
14
+ and migration directories via `nx g @anarchitects/nx-typeorm:bootstrap`.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ yarn add -D @anarchitects/nx-typeorm
20
+ ```
21
+
22
+ If you rely on TypeScript seeds or migrations, also add:
23
+
24
+ ```bash
25
+ yarn add -D ts-node typeorm-ts-node-commonjs
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ ### Bootstrap a project
31
+
32
+ ```bash
33
+ nx g @anarchitects/nx-typeorm:bootstrap api --withCompose
34
+ ```
35
+
36
+ Creates TypeORM configuration files, seed/migration directories, and patches
37
+ `app.module.ts` (for Nest apps) to use `TypeOrmModule.forRootAsync`.
38
+
39
+ ### Run migrations
40
+
41
+ ```bash
42
+ nx run api:run --transaction=each
43
+ ```
44
+
45
+ ### Generate a migration
46
+
47
+ ```bash
48
+ nx run api:generate --name AddUsers --driftCheck
49
+ ```
50
+
51
+ ### Revert migrations
52
+
53
+ ```bash
54
+ nx run api:revert --count=1
55
+ ```
56
+
57
+ ### Ensure schema
58
+
59
+ ```bash
60
+ DATABASE_URL=postgres://... nx run data-access:ensure-schema
61
+ ```
62
+
63
+ ### Seed data
64
+
65
+ ```bash
66
+ nx run api:seed --file tools/typeorm/seeds/index.ts --export runSeed
67
+ ```
68
+
69
+ Each executor forwards any extra CLI arguments to the underlying TypeORM tool,
70
+ making it easy to customize behavior.
71
+
72
+ ## Functionality Overview
73
+
74
+ - **Executors**: `generate`, `run`, `revert`, `ensure-schema`, and `seed` wrap
75
+ TypeORM commands with Nx-friendly ergonomics.
76
+ - **Generator**: `bootstrap` lays down TypeORM config, seeds, migrations, and
77
+ Nest integration boilerplate.
78
+ - **Inference**: Detects TypeORM projects and auto adds sensible default targets
79
+ when you run `nx graph` or `nx run` commands.
80
+
81
+ ## Tasks
82
+
83
+ - `nx build nx-typeorm` – build the plugin.
84
+ - `nx test nx-typeorm` – run Jest unit tests.
@@ -0,0 +1,10 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ import { type BaseExecutorOptions } from '../shared.js';
3
+ export interface EnsureSchemaExecutorOptions extends Pick<BaseExecutorOptions, 'projectRoot' | 'dataSource'> {
4
+ schema?: string;
5
+ tsconfig?: string;
6
+ }
7
+ export default function ensureSchema(options: EnsureSchemaExecutorOptions, context: ExecutorContext): Promise<{
8
+ success: boolean;
9
+ }>;
10
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/ensure-schema/executor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGlD,OAAO,EAIL,KAAK,mBAAmB,EACzB,MAAM,cAAc,CAAC;AAEtB,MAAM,WAAW,2BACf,SAAQ,IAAI,CAAC,mBAAmB,EAAE,aAAa,GAAG,YAAY,CAAC;IAC/D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAA8B,YAAY,CACxC,OAAO,EAAE,2BAA2B,EACpC,OAAO,EAAE,eAAe;;GAyEzB"}
@@ -0,0 +1,77 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { logger } from '@nx/devkit';
5
+ import { ensureProjectRoot, schemaFilePath, schemaNameFrom, } from '../shared.js';
6
+ export default async function ensureSchema(options, context) {
7
+ const { absoluteProjectRoot, dataSource: dataSourcePath } = ensureProjectRoot({ projectRoot: options.projectRoot, dataSource: options.dataSource }, context);
8
+ let schemaName = options.schema?.trim();
9
+ if (!schemaName) {
10
+ const candidate = schemaFilePath(absoluteProjectRoot);
11
+ if (existsSync(candidate)) {
12
+ const contents = readFileSync(candidate, 'utf-8');
13
+ schemaName = schemaNameFrom(contents);
14
+ }
15
+ }
16
+ if (!schemaName) {
17
+ throw new Error('Unable to infer schema name. Provide the schema option.');
18
+ }
19
+ const dataSource = await loadDataSource(dataSourcePath, absoluteProjectRoot, options.tsconfig);
20
+ try {
21
+ await dataSource.initialize();
22
+ const queryRunner = dataSource.createQueryRunner();
23
+ try {
24
+ if (typeof queryRunner.createSchema === 'function') {
25
+ await queryRunner.createSchema(schemaName, true);
26
+ logger.info(`Ensured schema "${schemaName}" exists.`);
27
+ }
28
+ else if (dataSource.options.type === 'mysql' ||
29
+ dataSource.options.type === 'mariadb') {
30
+ await queryRunner.query('CREATE DATABASE IF NOT EXISTS ??', [
31
+ schemaName,
32
+ ]);
33
+ logger.info(`Ensured database "${schemaName}" exists.`);
34
+ }
35
+ else if (dataSource.options.type === 'sqlite' ||
36
+ dataSource.options.type === 'better-sqlite3') {
37
+ logger.info('SQLite does not support schemas; ensure-schema is a no-op.');
38
+ }
39
+ else {
40
+ logger.warn('Current TypeORM driver does not expose createSchema; skipping ensure-schema.');
41
+ }
42
+ }
43
+ finally {
44
+ await queryRunner.release().catch((err) => {
45
+ logger.error(`Failed to release query runner: ${err instanceof Error ? err.message : String(err)}`);
46
+ });
47
+ }
48
+ return { success: true };
49
+ }
50
+ finally {
51
+ await dataSource.destroy().catch(() => undefined);
52
+ }
53
+ }
54
+ async function loadDataSource(dataSourcePath, absoluteProjectRoot, tsconfig) {
55
+ await registerTsNodeIfNeeded(dataSourcePath, absoluteProjectRoot, tsconfig);
56
+ const moduleUrl = pathToFileURL(dataSourcePath).href;
57
+ const imported = await import(moduleUrl);
58
+ const instance = imported.default ?? imported.dataSource ?? imported.appDataSource;
59
+ if (!instance || typeof instance.initialize !== 'function') {
60
+ throw new Error(`TypeORM DataSource not found in ${dataSourcePath}.`);
61
+ }
62
+ return instance;
63
+ }
64
+ async function registerTsNodeIfNeeded(dataSourcePath, projectRoot, tsconfig) {
65
+ if (!dataSourcePath.endsWith('.ts')) {
66
+ return;
67
+ }
68
+ if (tsconfig) {
69
+ process.env.TS_NODE_PROJECT = resolve(projectRoot, tsconfig);
70
+ }
71
+ try {
72
+ await import('ts-node/register');
73
+ }
74
+ catch {
75
+ throw new Error('ts-node is required to load TypeScript data sources. Install it in your workspace.');
76
+ }
77
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "title": "TypeORM Ensure Schema Executor",
4
+ "type": "object",
5
+ "properties": {
6
+ "projectRoot": {
7
+ "type": "string",
8
+ "description": "Project root when it cannot be inferred from the Nx project configuration."
9
+ },
10
+ "schema": {
11
+ "type": "string",
12
+ "description": "Database schema that should exist."
13
+ },
14
+ "dataSource": {
15
+ "type": "string",
16
+ "description": "Path to the TypeORM DataSource file. Inferred from the project when omitted."
17
+ },
18
+ "tsconfig": {
19
+ "type": "string",
20
+ "description": "Optional tsconfig used when loading a TypeScript DataSource file."
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,12 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ import { type BaseExecutorOptions } from '../shared.js';
3
+ export interface GenerateExecutorOptions extends BaseExecutorOptions {
4
+ name: string;
5
+ outputPath?: string;
6
+ pretty?: boolean;
7
+ driftCheck?: boolean;
8
+ }
9
+ export default function runGenerate(options: GenerateExecutorOptions, context: ExecutorContext): Promise<{
10
+ success: boolean;
11
+ }>;
12
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/generate/executor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAQL,KAAK,mBAAmB,EACzB,MAAM,cAAc,CAAC;AAGtB,MAAM,WAAW,uBAAwB,SAAQ,mBAAmB;IAClE,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,wBAA8B,WAAW,CACvC,OAAO,EAAE,uBAAuB,EAChC,OAAO,EAAE,eAAe;;GAyCzB"}
@@ -0,0 +1,39 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { getPackageManagerCommand } from '@nx/devkit';
4
+ import { defaultMigrationsDirectory, ensureArgs, ensureProjectRoot, normalizeName, projectTypeFor, relativeToWorkspace, splitCommand, } from '../shared.js';
5
+ import { spawn } from '../../utils/spawn.js';
6
+ export default async function runGenerate(options, context) {
7
+ if (!options.name || options.name.trim().length === 0) {
8
+ throw new Error('Provide a migration name via the name option.');
9
+ }
10
+ const normalizedName = normalizeName(options.name.trim());
11
+ const paths = ensureProjectRoot(options, context);
12
+ const projectType = projectTypeFor(context);
13
+ const outputDirectory = options.outputPath ??
14
+ defaultMigrationsDirectory(paths.projectRoot, projectType);
15
+ const targetPath = join(outputDirectory, normalizedName);
16
+ mkdirSync(dirname(targetPath), { recursive: true });
17
+ const pmc = getPackageManagerCommand();
18
+ const execCommand = pmc.exec ?? pmc.dlx ?? 'npx';
19
+ const [command, baseArgs] = splitCommand(execCommand);
20
+ const args = [
21
+ ...baseArgs,
22
+ 'typeorm-ts-node-commonjs',
23
+ 'migration:generate',
24
+ targetPath,
25
+ '-d',
26
+ relativeToWorkspace(context.root, paths.dataSource),
27
+ '-n',
28
+ normalizedName,
29
+ ];
30
+ if (options.pretty ?? true) {
31
+ args.push('--pretty');
32
+ }
33
+ if (options.driftCheck) {
34
+ args.push('--drift-check');
35
+ }
36
+ args.push(...ensureArgs(options.args));
37
+ const exitCode = await spawn(command, args, { cwd: context.root });
38
+ return { success: exitCode === 0 };
39
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "title": "TypeORM Generate Executor",
4
+ "type": "object",
5
+ "properties": {
6
+ "name": {
7
+ "type": "string",
8
+ "description": "Migration name used by TypeORM."
9
+ },
10
+ "projectRoot": {
11
+ "type": "string",
12
+ "description": "Project root when it cannot be inferred from the Nx project configuration."
13
+ },
14
+ "dataSource": {
15
+ "type": "string",
16
+ "description": "Path to the TypeORM data source file used for migrations."
17
+ },
18
+ "outputPath": {
19
+ "type": "string",
20
+ "description": "Directory where generated migrations will be placed."
21
+ },
22
+ "pretty": {
23
+ "type": "boolean",
24
+ "description": "Enable pretty printing for generated migrations.",
25
+ "default": true
26
+ },
27
+ "driftCheck": {
28
+ "type": "boolean",
29
+ "description": "Enable drift check before generating migrations."
30
+ },
31
+ "args": {
32
+ "type": "array",
33
+ "items": {
34
+ "type": "string"
35
+ },
36
+ "description": "Additional CLI arguments passed through to the TypeORM command."
37
+ }
38
+ },
39
+ "required": ["name"]
40
+ }
@@ -0,0 +1,10 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ import { type BaseExecutorOptions } from '../shared.js';
3
+ export interface RevertExecutorOptions extends BaseExecutorOptions {
4
+ count?: number;
5
+ args?: string[];
6
+ }
7
+ export default function revertMigrations(options: RevertExecutorOptions, context: ExecutorContext): Promise<{
8
+ success: boolean;
9
+ }>;
10
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/revert/executor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAKL,KAAK,mBAAmB,EACzB,MAAM,cAAc,CAAC;AAGtB,MAAM,WAAW,qBAAsB,SAAQ,mBAAmB;IAChE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,wBAA8B,gBAAgB,CAC5C,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,eAAe;;GAwBzB"}
@@ -0,0 +1,22 @@
1
+ import { getPackageManagerCommand } from '@nx/devkit';
2
+ import { ensureArgs, ensureProjectRoot, relativeToWorkspace, splitCommand, } from '../shared.js';
3
+ import { spawn } from '../../utils/spawn.js';
4
+ export default async function revertMigrations(options, context) {
5
+ const paths = ensureProjectRoot(options, context);
6
+ const pmc = getPackageManagerCommand();
7
+ const execCommand = pmc.exec ?? pmc.dlx ?? 'npx';
8
+ const [command, baseArgs] = splitCommand(execCommand);
9
+ const args = [
10
+ ...baseArgs,
11
+ 'typeorm-ts-node-commonjs',
12
+ 'migration:revert',
13
+ '-d',
14
+ relativeToWorkspace(context.root, paths.dataSource),
15
+ ];
16
+ if (options.count && options.count > 0) {
17
+ args.push('--revert', String(options.count));
18
+ }
19
+ args.push(...ensureArgs(options.args));
20
+ const exitCode = await spawn(command, args, { cwd: context.root });
21
+ return { success: exitCode === 0 };
22
+ }
@@ -0,0 +1,27 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "title": "TypeORM Revert Executor",
4
+ "type": "object",
5
+ "properties": {
6
+ "projectRoot": {
7
+ "type": "string",
8
+ "description": "Project root when it cannot be inferred from the Nx project configuration."
9
+ },
10
+ "dataSource": {
11
+ "type": "string",
12
+ "description": "Path to the TypeORM data source file used for migrations."
13
+ },
14
+ "count": {
15
+ "type": "integer",
16
+ "minimum": 1,
17
+ "description": "Number of migrations to revert."
18
+ },
19
+ "args": {
20
+ "type": "array",
21
+ "items": {
22
+ "type": "string"
23
+ },
24
+ "description": "Additional CLI arguments passed through to the TypeORM command."
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,11 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ import { type BaseExecutorOptions } from '../shared.js';
3
+ export interface RunExecutorOptions extends BaseExecutorOptions {
4
+ transaction?: 'all' | 'none' | 'each';
5
+ fake?: boolean;
6
+ args?: string[];
7
+ }
8
+ export default function runMigrations(options: RunExecutorOptions, context: ExecutorContext): Promise<{
9
+ success: boolean;
10
+ }>;
11
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/run/executor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAKL,KAAK,mBAAmB,EACzB,MAAM,cAAc,CAAC;AAGtB,MAAM,WAAW,kBAAmB,SAAQ,mBAAmB;IAC7D,WAAW,CAAC,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;IACtC,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,wBAA8B,aAAa,CACzC,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,eAAe;;GA2BzB"}
@@ -0,0 +1,25 @@
1
+ import { getPackageManagerCommand } from '@nx/devkit';
2
+ import { ensureArgs, ensureProjectRoot, relativeToWorkspace, splitCommand, } from '../shared.js';
3
+ import { spawn } from '../../utils/spawn.js';
4
+ export default async function runMigrations(options, context) {
5
+ const paths = ensureProjectRoot(options, context);
6
+ const pmc = getPackageManagerCommand();
7
+ const execCommand = pmc.exec ?? pmc.dlx ?? 'npx';
8
+ const [command, baseArgs] = splitCommand(execCommand);
9
+ const args = [
10
+ ...baseArgs,
11
+ 'typeorm-ts-node-commonjs',
12
+ 'migration:run',
13
+ '-d',
14
+ relativeToWorkspace(context.root, paths.dataSource),
15
+ ];
16
+ if (options.transaction) {
17
+ args.push('--transaction', options.transaction);
18
+ }
19
+ if (options.fake) {
20
+ args.push('--fake');
21
+ }
22
+ args.push(...ensureArgs(options.args));
23
+ const exitCode = await spawn(command, args, { cwd: context.root });
24
+ return { success: exitCode === 0 };
25
+ }
@@ -0,0 +1,31 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "title": "TypeORM Run Executor",
4
+ "type": "object",
5
+ "properties": {
6
+ "projectRoot": {
7
+ "type": "string",
8
+ "description": "Project root when it cannot be inferred from the Nx project configuration."
9
+ },
10
+ "dataSource": {
11
+ "type": "string",
12
+ "description": "Path to the TypeORM data source file used for migrations."
13
+ },
14
+ "transaction": {
15
+ "type": "string",
16
+ "enum": ["all", "each", "none"],
17
+ "description": "Transaction mode passed to the TypeORM CLI."
18
+ },
19
+ "fake": {
20
+ "type": "boolean",
21
+ "description": "Mark migrations as executed without running them."
22
+ },
23
+ "args": {
24
+ "type": "array",
25
+ "items": {
26
+ "type": "string"
27
+ },
28
+ "description": "Additional CLI arguments passed through to the TypeORM command."
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,12 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ import { type BaseExecutorOptions } from '../shared.js';
3
+ export interface SeedExecutorOptions extends Pick<BaseExecutorOptions, 'projectRoot'> {
4
+ file: string;
5
+ export?: string;
6
+ tsconfig?: string;
7
+ args?: unknown[];
8
+ }
9
+ export default function seedDatabase(options: SeedExecutorOptions, context: ExecutorContext): Promise<{
10
+ success: boolean;
11
+ }>;
12
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/executors/seed/executor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,OAAO,EAAsB,KAAK,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAE5E,MAAM,WAAW,mBACf,SAAQ,IAAI,CAAC,mBAAmB,EAAE,aAAa,CAAC;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC;CAClB;AAED,wBAA8B,YAAY,CACxC,OAAO,EAAE,mBAAmB,EAC5B,OAAO,EAAE,eAAe;;GAsCzB"}
@@ -0,0 +1,44 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { logger } from '@nx/devkit';
5
+ import { resolveProjectRoot } from '../shared.js';
6
+ export default async function seedDatabase(options, context) {
7
+ if (!options.file) {
8
+ throw new Error('Provide a seed file using the file option.');
9
+ }
10
+ const { absoluteProjectRoot } = resolveProjectRoot(options.projectRoot, context);
11
+ const scriptPath = isAbsolute(options.file)
12
+ ? options.file
13
+ : resolve(absoluteProjectRoot, options.file);
14
+ if (!existsSync(scriptPath)) {
15
+ throw new Error(`Seed file not found at ${scriptPath}`);
16
+ }
17
+ if (scriptPath.endsWith('.ts')) {
18
+ await registerTsNode(options, absoluteProjectRoot);
19
+ }
20
+ const moduleUrl = pathToFileURL(scriptPath).href;
21
+ const imported = await import(moduleUrl);
22
+ const exportName = options.export ?? 'default';
23
+ const runner = exportName === 'default' ? imported.default : imported[exportName];
24
+ if (typeof runner !== 'function') {
25
+ throw new Error(`Export "${exportName}" is not a function in ${scriptPath}.`);
26
+ }
27
+ const result = await runner(options.args ?? []);
28
+ logger.info(`Executed seed from ${scriptPath} using export ${exportName}.`);
29
+ return { success: result !== false };
30
+ }
31
+ async function registerTsNode(options, absoluteProjectRoot) {
32
+ const tsconfigPath = options.tsconfig
33
+ ? resolve(absoluteProjectRoot, options.tsconfig)
34
+ : undefined;
35
+ if (tsconfigPath) {
36
+ process.env.TS_NODE_PROJECT = tsconfigPath;
37
+ }
38
+ try {
39
+ await import('ts-node/register');
40
+ }
41
+ catch {
42
+ throw new Error('ts-node is required to execute TypeScript seeds. Install it in your workspace.');
43
+ }
44
+ }
@@ -0,0 +1,31 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "title": "TypeORM Seed Executor",
4
+ "type": "object",
5
+ "properties": {
6
+ "projectRoot": {
7
+ "type": "string",
8
+ "description": "Project root when it cannot be inferred from the Nx project configuration."
9
+ },
10
+ "file": {
11
+ "type": "string",
12
+ "description": "Path to the seed script to execute."
13
+ },
14
+ "export": {
15
+ "type": "string",
16
+ "description": "Named export that should be executed. Defaults to default export."
17
+ },
18
+ "tsconfig": {
19
+ "type": "string",
20
+ "description": "Path to the tsconfig used when registering ts-node for TypeScript seeds."
21
+ },
22
+ "args": {
23
+ "type": "array",
24
+ "items": {
25
+ "type": "string"
26
+ },
27
+ "description": "Arguments passed to the seed function."
28
+ }
29
+ },
30
+ "required": ["file"]
31
+ }
@@ -0,0 +1,25 @@
1
+ import type { ExecutorContext } from '@nx/devkit';
2
+ export interface BaseExecutorOptions {
3
+ projectRoot?: string;
4
+ dataSource?: string;
5
+ args?: string[];
6
+ }
7
+ export interface WorkspacePaths {
8
+ projectRoot: string;
9
+ absoluteProjectRoot: string;
10
+ dataSource: string;
11
+ }
12
+ export declare function ensureProjectRoot(options: BaseExecutorOptions, context: ExecutorContext): WorkspacePaths;
13
+ export declare function resolveProjectRoot(configuredRoot: string | undefined, context: ExecutorContext): {
14
+ projectRoot: string;
15
+ absoluteProjectRoot: string;
16
+ };
17
+ export declare function splitCommand(command: string): [string, string[]];
18
+ export declare function relativeToWorkspace(root: string, filePath: string): string;
19
+ export declare function defaultMigrationsDirectory(projectRoot: string, projectType: 'application' | 'library' | undefined): string;
20
+ export declare function ensureArgs(options?: string[]): string[];
21
+ export declare function projectTypeFor(context: ExecutorContext): 'application' | 'library' | undefined;
22
+ export declare function schemaFilePath(projectRoot: string): string;
23
+ export declare function schemaNameFrom(contents: string): string | undefined;
24
+ export declare function normalizeName(name: string): string;
25
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/executors/shared.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,MAAM,WAAW,mBAAmB;IAClC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;CACpB;AASD,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,mBAAmB,EAC5B,OAAO,EAAE,eAAe,GACvB,cAAc,CAShB;AAED,wBAAgB,kBAAkB,CAChC,cAAc,EAAE,MAAM,GAAG,SAAS,EAClC,OAAO,EAAE,eAAe,GACvB;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,mBAAmB,EAAE,MAAM,CAAA;CAAE,CActD;AA4BD,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAGhE;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE1E;AAED,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,aAAa,GAAG,SAAS,GAAG,SAAS,GACjD,MAAM,CAMR;AAED,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAEvD;AAED,wBAAgB,cAAc,CAC5B,OAAO,EAAE,eAAe,GACvB,aAAa,GAAG,SAAS,GAAG,SAAS,CAGvC;AAED,wBAAgB,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGnE;AAED,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD"}
@@ -0,0 +1,71 @@
1
+ import { isAbsolute, join, relative, resolve } from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ const CANDIDATE_DATASOURCES = [
4
+ 'tools/typeorm/datasource.migrations.ts',
5
+ 'tools/typeorm/datasource.migrations.js',
6
+ 'src/typeorm.datasource.ts',
7
+ 'src/typeorm.datasource.js',
8
+ ];
9
+ export function ensureProjectRoot(options, context) {
10
+ const { projectRoot, absoluteProjectRoot } = resolveProjectRoot(options.projectRoot, context);
11
+ const dataSource = resolveDataSource(options.dataSource, absoluteProjectRoot);
12
+ return { projectRoot, absoluteProjectRoot, dataSource };
13
+ }
14
+ export function resolveProjectRoot(configuredRoot, context) {
15
+ const projectConfig = context.projectsConfigurations?.projects?.[context.projectName ?? ''];
16
+ const projectRoot = configuredRoot ?? projectConfig?.root;
17
+ if (!projectRoot) {
18
+ throw new Error('Unable to determine project root. Provide projectRoot.');
19
+ }
20
+ const absoluteProjectRoot = isAbsolute(projectRoot)
21
+ ? projectRoot
22
+ : resolve(context.root, projectRoot);
23
+ return { projectRoot, absoluteProjectRoot };
24
+ }
25
+ function resolveDataSource(explicit, absoluteProjectRoot) {
26
+ if (explicit) {
27
+ return absoluteFrom(explicit, absoluteProjectRoot);
28
+ }
29
+ for (const candidate of CANDIDATE_DATASOURCES) {
30
+ const absoluteCandidate = join(absoluteProjectRoot, candidate);
31
+ if (existsSync(absoluteCandidate)) {
32
+ return absoluteCandidate;
33
+ }
34
+ }
35
+ throw new Error('Unable to locate a TypeORM data source. Add one or pass the dataSource option.');
36
+ }
37
+ function absoluteFrom(pathValue, absoluteProjectRoot) {
38
+ return isAbsolute(pathValue)
39
+ ? pathValue
40
+ : resolve(absoluteProjectRoot, pathValue);
41
+ }
42
+ export function splitCommand(command) {
43
+ const [cmd, ...rest] = command.split(' ');
44
+ return [cmd, rest];
45
+ }
46
+ export function relativeToWorkspace(root, filePath) {
47
+ return relative(root, filePath) || '.';
48
+ }
49
+ export function defaultMigrationsDirectory(projectRoot, projectType) {
50
+ if (projectType === 'application') {
51
+ return join(projectRoot, 'tools/typeorm/migrations');
52
+ }
53
+ return join(projectRoot, 'src/infrastructure-persistence/migrations');
54
+ }
55
+ export function ensureArgs(options) {
56
+ return options?.filter((arg) => arg.trim().length > 0) ?? [];
57
+ }
58
+ export function projectTypeFor(context) {
59
+ return context.projectsConfigurations?.projects?.[context.projectName ?? '']
60
+ ?.projectType;
61
+ }
62
+ export function schemaFilePath(projectRoot) {
63
+ return join(projectRoot, 'src/infrastructure-persistence/schema.ts');
64
+ }
65
+ export function schemaNameFrom(contents) {
66
+ const match = contents.match(/SCHEMA\s*=\s*['"]([^'"\s]+)['"]/);
67
+ return match?.[1];
68
+ }
69
+ export function normalizeName(name) {
70
+ return name.replace(/\s+/g, '-');
71
+ }
@@ -0,0 +1,19 @@
1
+ version: "3.8"
2
+ services:
3
+ db:
4
+ image: postgres:16-alpine
5
+ environment:
6
+ POSTGRES_USER: postgres
7
+ POSTGRES_PASSWORD: postgres
8
+ POSTGRES_DB: <%= appDatabase %>
9
+ ports:
10
+ - "5432:5432"
11
+ healthcheck:
12
+ test: ["CMD-SHELL", "pg_isready -U postgres -d <%= appDatabase %>"]
13
+ interval: 2s
14
+ timeout: 2s
15
+ retries: 30
16
+ volumes:
17
+ - pgdata:/var/lib/postgresql/data
18
+ volumes:
19
+ pgdata: {}
@@ -0,0 +1 @@
1
+ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/<%= appDatabase %>