@anarchitects/nx-typeorm 0.3.0 → 0.4.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/generators/bootstrap/files/app/src/data-source.ts__tmpl__ +55 -2
- package/dist/generators/bootstrap/files/app/src/typeorm.datasource.ts__tmpl__ +2 -1
- package/dist/generators/bootstrap/files/app/tools/typeorm/datasource.migrations.ts__tmpl__ +57 -2
- package/dist/generators/bootstrap/generator.d.ts +1 -0
- package/dist/generators/bootstrap/generator.d.ts.map +1 -1
- package/dist/generators/bootstrap/generator.js +99 -28
- package/dist/generators/bootstrap/schema.json +5 -0
- package/dist/generators/entity-create/generator.d.ts.map +1 -1
- package/dist/generators/entity-create/generator.js +15 -4
- package/dist/generators/subscriber-create/generator.d.ts.map +1 -1
- package/dist/generators/subscriber-create/generator.js +15 -4
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +9 -1
- package/dist/utils/shared.d.ts +1 -0
- package/dist/utils/shared.d.ts.map +1 -1
- package/dist/utils/shared.js +6 -0
- package/package.json +3 -6
- package/dist/generators/bootstrap/files/app/tools/typeorm/connection-options.ts__tmpl__ +0 -292
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
import { DataSource } from 'typeorm';
|
|
2
|
-
|
|
2
|
+
|
|
3
|
+
export const AppDataSource = new DataSource({
|
|
4
|
+
<% if (database === 'postgres') { %> type: 'postgres',
|
|
5
|
+
host: process.env.TYPEORM_HOST ?? 'localhost',
|
|
6
|
+
port: Number.parseInt(process.env.TYPEORM_PORT ?? '5432', 10) || 5432,
|
|
7
|
+
username: process.env.TYPEORM_USERNAME ?? 'postgres',
|
|
8
|
+
password: process.env.TYPEORM_PASSWORD ?? 'postgres',
|
|
9
|
+
database: process.env.TYPEORM_DATABASE ?? '<%= appDatabase %>',
|
|
10
|
+
schema: process.env.TYPEORM_SCHEMA ?? 'public',
|
|
11
|
+
ssl: process.env.TYPEORM_SSL === 'true',
|
|
12
|
+
applicationName: process.env.TYPEORM_APPLICATION_NAME ?? '<%= appDatabase %>-service',
|
|
13
|
+
connectTimeoutMS: Number.parseInt(process.env.TYPEORM_CONNECT_TIMEOUT_MS ?? '5000', 10) || 5000,
|
|
14
|
+
<% } %><% if (database === 'mysql' || database === 'mariadb') { %> type: '<%= database %>',
|
|
15
|
+
host: process.env.TYPEORM_HOST ?? 'localhost',
|
|
16
|
+
port: Number.parseInt(process.env.TYPEORM_PORT ?? '3306', 10) || 3306,
|
|
17
|
+
username: process.env.TYPEORM_USERNAME ?? 'root',
|
|
18
|
+
password: process.env.TYPEORM_PASSWORD ?? 'root',
|
|
19
|
+
database: process.env.TYPEORM_DATABASE ?? '<%= appDatabase %>',
|
|
20
|
+
ssl: process.env.TYPEORM_SSL === 'true',
|
|
21
|
+
socketPath: process.env.TYPEORM_SOCKET_PATH?.trim() || undefined,
|
|
22
|
+
charset: process.env.TYPEORM_CHARSET ?? 'utf8mb4',
|
|
23
|
+
timezone: process.env.TYPEORM_TIMEZONE ?? 'Z',
|
|
24
|
+
connectTimeout: Number.parseInt(process.env.TYPEORM_CONNECT_TIMEOUT ?? '10000', 10) || 10000,
|
|
25
|
+
<% } %><% if (database === 'sqlite') { %> type: 'sqlite',
|
|
26
|
+
database: process.env.TYPEORM_DATABASE ?? './tmp/<%= appDatabase %>.sqlite',
|
|
27
|
+
busyTimeout: Number.parseInt(process.env.TYPEORM_BUSY_TIMEOUT ?? '5000', 10) || 5000,
|
|
28
|
+
enableWAL: process.env.TYPEORM_ENABLE_WAL === undefined ? true : process.env.TYPEORM_ENABLE_WAL === 'true',
|
|
29
|
+
<% } %><% if (database === 'better-sqlite3') { %> type: 'better-sqlite3',
|
|
30
|
+
database: process.env.TYPEORM_DATABASE ?? './tmp/<%= appDatabase %>.sqlite',
|
|
31
|
+
enableWAL: process.env.TYPEORM_ENABLE_WAL === undefined ? true : process.env.TYPEORM_ENABLE_WAL === 'true',
|
|
32
|
+
timeout: Number.parseInt(process.env.TYPEORM_TIMEOUT ?? '5000', 10) || 5000,
|
|
33
|
+
readonly: process.env.TYPEORM_READONLY === 'true',
|
|
34
|
+
fileMustExist: process.env.TYPEORM_FILE_MUST_EXIST === 'true',
|
|
35
|
+
statementCacheSize: Number.parseInt(process.env.TYPEORM_STATEMENT_CACHE_SIZE ?? '100', 10) || 100,
|
|
36
|
+
<% } %><% if (database === 'mssql') { %> type: 'mssql',
|
|
37
|
+
host: process.env.TYPEORM_HOST ?? 'localhost',
|
|
38
|
+
port: Number.parseInt(process.env.TYPEORM_PORT ?? '1433', 10) || 1433,
|
|
39
|
+
username: process.env.TYPEORM_USERNAME ?? 'sa',
|
|
40
|
+
password: process.env.TYPEORM_PASSWORD ?? 'StrongPassword!123',
|
|
41
|
+
database: process.env.TYPEORM_DATABASE ?? '<%= appDatabase %>',
|
|
42
|
+
domain: process.env.TYPEORM_DOMAIN?.trim() || undefined,
|
|
43
|
+
connectionTimeout: Number.parseInt(process.env.TYPEORM_CONNECTION_TIMEOUT ?? '15000', 10) || 15000,
|
|
44
|
+
requestTimeout: Number.parseInt(process.env.TYPEORM_REQUEST_TIMEOUT ?? '15000', 10) || 15000,
|
|
45
|
+
options: {
|
|
46
|
+
encrypt: process.env.TYPEORM_ENCRYPT === 'true',
|
|
47
|
+
trustServerCertificate:
|
|
48
|
+
process.env.TYPEORM_TRUST_SERVER_CERTIFICATE === undefined
|
|
49
|
+
? true
|
|
50
|
+
: process.env.TYPEORM_TRUST_SERVER_CERTIFICATE === 'true',
|
|
51
|
+
instanceName: process.env.TYPEORM_INSTANCE_NAME?.trim() || undefined,
|
|
52
|
+
},
|
|
53
|
+
<% } %> synchronize: false,
|
|
54
|
+
logging: false,
|
|
55
|
+
});
|
|
3
56
|
|
|
4
57
|
export function makeRuntimeDataSource(): DataSource {
|
|
5
|
-
return new DataSource(
|
|
58
|
+
return new DataSource(AppDataSource.options);
|
|
6
59
|
}
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export { makeRuntimeDataSource } from './data-source';
|
|
1
|
+
export { AppDataSource, makeRuntimeDataSource } from './data-source';
|
|
2
|
+
export { AppDataSource as default } from './data-source';
|
|
@@ -1,4 +1,59 @@
|
|
|
1
1
|
import { DataSource } from 'typeorm';
|
|
2
|
-
import { createMigrationDataSourceOptions } from './connection-options';
|
|
3
2
|
|
|
4
|
-
|
|
3
|
+
const MigrationDataSource = new DataSource({
|
|
4
|
+
<% if (database === 'postgres') { %> type: 'postgres',
|
|
5
|
+
host: process.env.TYPEORM_HOST ?? 'localhost',
|
|
6
|
+
port: Number.parseInt(process.env.TYPEORM_PORT ?? '5432', 10) || 5432,
|
|
7
|
+
username: process.env.TYPEORM_USERNAME ?? 'postgres',
|
|
8
|
+
password: process.env.TYPEORM_PASSWORD ?? 'postgres',
|
|
9
|
+
database: process.env.TYPEORM_DATABASE ?? '<%= appDatabase %>',
|
|
10
|
+
schema: process.env.TYPEORM_SCHEMA ?? 'public',
|
|
11
|
+
ssl: process.env.TYPEORM_SSL === 'true',
|
|
12
|
+
applicationName: process.env.TYPEORM_APPLICATION_NAME ?? '<%= appDatabase %>-service',
|
|
13
|
+
connectTimeoutMS: Number.parseInt(process.env.TYPEORM_CONNECT_TIMEOUT_MS ?? '5000', 10) || 5000,
|
|
14
|
+
<% } %><% if (database === 'mysql' || database === 'mariadb') { %> type: '<%= database %>',
|
|
15
|
+
host: process.env.TYPEORM_HOST ?? 'localhost',
|
|
16
|
+
port: Number.parseInt(process.env.TYPEORM_PORT ?? '3306', 10) || 3306,
|
|
17
|
+
username: process.env.TYPEORM_USERNAME ?? 'root',
|
|
18
|
+
password: process.env.TYPEORM_PASSWORD ?? 'root',
|
|
19
|
+
database: process.env.TYPEORM_DATABASE ?? '<%= appDatabase %>',
|
|
20
|
+
ssl: process.env.TYPEORM_SSL === 'true',
|
|
21
|
+
socketPath: process.env.TYPEORM_SOCKET_PATH?.trim() || undefined,
|
|
22
|
+
charset: process.env.TYPEORM_CHARSET ?? 'utf8mb4',
|
|
23
|
+
timezone: process.env.TYPEORM_TIMEZONE ?? 'Z',
|
|
24
|
+
connectTimeout: Number.parseInt(process.env.TYPEORM_CONNECT_TIMEOUT ?? '10000', 10) || 10000,
|
|
25
|
+
<% } %><% if (database === 'sqlite') { %> type: 'sqlite',
|
|
26
|
+
database: process.env.TYPEORM_DATABASE ?? './tmp/<%= appDatabase %>.sqlite',
|
|
27
|
+
busyTimeout: Number.parseInt(process.env.TYPEORM_BUSY_TIMEOUT ?? '5000', 10) || 5000,
|
|
28
|
+
enableWAL: process.env.TYPEORM_ENABLE_WAL === undefined ? true : process.env.TYPEORM_ENABLE_WAL === 'true',
|
|
29
|
+
<% } %><% if (database === 'better-sqlite3') { %> type: 'better-sqlite3',
|
|
30
|
+
database: process.env.TYPEORM_DATABASE ?? './tmp/<%= appDatabase %>.sqlite',
|
|
31
|
+
enableWAL: process.env.TYPEORM_ENABLE_WAL === undefined ? true : process.env.TYPEORM_ENABLE_WAL === 'true',
|
|
32
|
+
timeout: Number.parseInt(process.env.TYPEORM_TIMEOUT ?? '5000', 10) || 5000,
|
|
33
|
+
readonly: process.env.TYPEORM_READONLY === 'true',
|
|
34
|
+
fileMustExist: process.env.TYPEORM_FILE_MUST_EXIST === 'true',
|
|
35
|
+
statementCacheSize: Number.parseInt(process.env.TYPEORM_STATEMENT_CACHE_SIZE ?? '100', 10) || 100,
|
|
36
|
+
<% } %><% if (database === 'mssql') { %> type: 'mssql',
|
|
37
|
+
host: process.env.TYPEORM_HOST ?? 'localhost',
|
|
38
|
+
port: Number.parseInt(process.env.TYPEORM_PORT ?? '1433', 10) || 1433,
|
|
39
|
+
username: process.env.TYPEORM_USERNAME ?? 'sa',
|
|
40
|
+
password: process.env.TYPEORM_PASSWORD ?? 'StrongPassword!123',
|
|
41
|
+
database: process.env.TYPEORM_DATABASE ?? '<%= appDatabase %>',
|
|
42
|
+
domain: process.env.TYPEORM_DOMAIN?.trim() || undefined,
|
|
43
|
+
connectionTimeout: Number.parseInt(process.env.TYPEORM_CONNECTION_TIMEOUT ?? '15000', 10) || 15000,
|
|
44
|
+
requestTimeout: Number.parseInt(process.env.TYPEORM_REQUEST_TIMEOUT ?? '15000', 10) || 15000,
|
|
45
|
+
options: {
|
|
46
|
+
encrypt: process.env.TYPEORM_ENCRYPT === 'true',
|
|
47
|
+
trustServerCertificate:
|
|
48
|
+
process.env.TYPEORM_TRUST_SERVER_CERTIFICATE === undefined
|
|
49
|
+
? true
|
|
50
|
+
: process.env.TYPEORM_TRUST_SERVER_CERTIFICATE === 'true',
|
|
51
|
+
instanceName: process.env.TYPEORM_INSTANCE_NAME?.trim() || undefined,
|
|
52
|
+
},
|
|
53
|
+
<% } %> entities: [],
|
|
54
|
+
migrations: ['dist/tools/typeorm/migrations/*.js'],
|
|
55
|
+
synchronize: false,
|
|
56
|
+
logging: false,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
export default MigrationDataSource;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/bootstrap/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAQL,IAAI,EAEJ,KAAK,iBAAiB,EACvB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/bootstrap/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAQL,IAAI,EAEJ,KAAK,iBAAiB,EACvB,MAAM,YAAY,CAAC;AAkBpB,UAAU,wBAAwB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,EAAE,CAAC,EAAE,iBAAiB,GAAG,YAAY,CAAC;IACtC,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAOD,QAAA,MAAM,mBAAmB,gFAOf,CAAC;AAWX,KAAK,iBAAiB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAmB9D,wBAA8B,kBAAkB,CAC9C,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,wBAAwB,8BA4ClC"}
|
|
@@ -19,11 +19,9 @@ const DEFAULT_SCHEMA_PATH = 'src/infrastructure-persistence/schema.ts';
|
|
|
19
19
|
const DEFAULT_MIGRATIONS_DIR = 'src/infrastructure-persistence/migrations';
|
|
20
20
|
const DEFAULT_MIGRATION_FILE = '1700000000000_init_schema.ts';
|
|
21
21
|
const APP_MIGRATIONS_DATASOURCE_PATH = 'tools/typeorm/datasource.migrations.ts';
|
|
22
|
+
const APP_CONNECTION_OPTIONS_PATH = 'tools/typeorm/connection-options.ts';
|
|
22
23
|
const runtimeImportPath = './data-source';
|
|
23
|
-
const SUPPORTED_DATABASE_DISPLAY = [
|
|
24
|
-
...SUPPORTED_DATABASES,
|
|
25
|
-
'postgresql',
|
|
26
|
-
].join(', ');
|
|
24
|
+
const SUPPORTED_DATABASE_DISPLAY = [...SUPPORTED_DATABASES, 'postgresql'].join(', ');
|
|
27
25
|
const DRIVER_DEPENDENCIES = {
|
|
28
26
|
postgres: { packageName: 'pg', version: '^8.20.0' },
|
|
29
27
|
mysql: { packageName: 'mysql2', version: '^3.20.0' },
|
|
@@ -35,14 +33,12 @@ const DRIVER_DEPENDENCIES = {
|
|
|
35
33
|
export default async function bootstrapGenerator(tree, options) {
|
|
36
34
|
const database = normalizeDatabase(options.db);
|
|
37
35
|
const project = readProjectConfiguration(tree, options.project);
|
|
38
|
-
const
|
|
39
|
-
|
|
36
|
+
const applicationBootstrapMode = project.projectType === 'application'
|
|
37
|
+
? resolveApplicationBootstrapMode(tree, options.project, project.root, project.sourceRoot)
|
|
38
|
+
: 'plain';
|
|
39
|
+
const isNestApplication = applicationBootstrapMode === 'nest';
|
|
40
40
|
const tasks = [];
|
|
41
|
-
const dependencyTask = addDependenciesToPackageJson(tree, buildRuntimeDependencies(database, isNestApplication),
|
|
42
|
-
'ts-node': '^10.9.2',
|
|
43
|
-
'typeorm-ts-node-commonjs': '^0.3.20',
|
|
44
|
-
'typeorm-ts-node-esm': '^0.3.20',
|
|
45
|
-
});
|
|
41
|
+
const dependencyTask = addDependenciesToPackageJson(tree, buildRuntimeDependencies(database, isNestApplication), buildToolDependencies());
|
|
46
42
|
if (!options.skipInstall) {
|
|
47
43
|
tasks.push(dependencyTask);
|
|
48
44
|
}
|
|
@@ -70,6 +66,13 @@ function buildRuntimeDependencies(database, isNestApplication) {
|
|
|
70
66
|
}
|
|
71
67
|
return dependencies;
|
|
72
68
|
}
|
|
69
|
+
function buildToolDependencies() {
|
|
70
|
+
return {
|
|
71
|
+
'ts-node': '^10.9.2',
|
|
72
|
+
'typeorm-ts-node-commonjs': '^0.3.20',
|
|
73
|
+
'typeorm-ts-node-esm': '^0.3.20',
|
|
74
|
+
};
|
|
75
|
+
}
|
|
73
76
|
function prepareLibrary(tree, projectName, projectRoot, options) {
|
|
74
77
|
if (!options.domain) {
|
|
75
78
|
throw new Error('Domain option is required when targeting a library.');
|
|
@@ -117,6 +120,7 @@ function prepareApplication(tree, projectRoot, sourceRoot, options, isNestApplic
|
|
|
117
120
|
const database = normalizeDatabase(options.db);
|
|
118
121
|
const projectName = names(options.project).fileName.replace(/-/g, '_');
|
|
119
122
|
const migrationsDatasourcePath = joinPathFragments(projectRoot, APP_MIGRATIONS_DATASOURCE_PATH);
|
|
123
|
+
const connectionOptionsPath = joinPathFragments(projectRoot, APP_CONNECTION_OPTIONS_PATH);
|
|
120
124
|
const existingMigrationsDatasource = tree.exists(migrationsDatasourcePath)
|
|
121
125
|
? tree.read(migrationsDatasourcePath)
|
|
122
126
|
: null;
|
|
@@ -125,9 +129,17 @@ function prepareApplication(tree, projectRoot, sourceRoot, options, isNestApplic
|
|
|
125
129
|
database,
|
|
126
130
|
appDatabase: projectName,
|
|
127
131
|
});
|
|
128
|
-
if (existingMigrationsDatasource) {
|
|
132
|
+
if (options.migrationDatasource && existingMigrationsDatasource) {
|
|
129
133
|
tree.write(migrationsDatasourcePath, existingMigrationsDatasource);
|
|
130
134
|
}
|
|
135
|
+
else if (!options.migrationDatasource &&
|
|
136
|
+
tree.exists(migrationsDatasourcePath)) {
|
|
137
|
+
tree.delete(migrationsDatasourcePath);
|
|
138
|
+
}
|
|
139
|
+
// Legacy helper template is no longer generated; clean up when re-running.
|
|
140
|
+
if (tree.exists(connectionOptionsPath)) {
|
|
141
|
+
tree.delete(connectionOptionsPath);
|
|
142
|
+
}
|
|
131
143
|
if (!options.withCompose) {
|
|
132
144
|
const composePath = joinPathFragments(projectRoot, 'docker-compose.yml');
|
|
133
145
|
if (tree.exists(composePath)) {
|
|
@@ -137,6 +149,9 @@ function prepareApplication(tree, projectRoot, sourceRoot, options, isNestApplic
|
|
|
137
149
|
if (isNestApplication) {
|
|
138
150
|
patchAppModule(tree, projectRoot, sourceRoot);
|
|
139
151
|
}
|
|
152
|
+
else {
|
|
153
|
+
patchMainFile(tree, projectRoot, sourceRoot);
|
|
154
|
+
}
|
|
140
155
|
}
|
|
141
156
|
function normalizeDatabase(database) {
|
|
142
157
|
const normalized = (database ?? DEFAULT_DATABASE).trim().toLowerCase();
|
|
@@ -217,9 +232,20 @@ function normalizeProjectRelative(pathValue) {
|
|
|
217
232
|
}
|
|
218
233
|
return normalized;
|
|
219
234
|
}
|
|
220
|
-
function
|
|
235
|
+
function resolveApplicationBootstrapMode(tree, projectName, projectRoot, sourceRoot) {
|
|
221
236
|
const resolvedSourceRoot = sourceRoot ?? joinPathFragments(projectRoot, 'src');
|
|
222
|
-
|
|
237
|
+
if (tree.exists(joinPathFragments(resolvedSourceRoot, 'app.module.ts'))) {
|
|
238
|
+
return 'nest';
|
|
239
|
+
}
|
|
240
|
+
const mainPath = joinPathFragments(resolvedSourceRoot, 'main.ts');
|
|
241
|
+
const mainSource = tree.exists(mainPath)
|
|
242
|
+
? tree.read(mainPath, 'utf-8')
|
|
243
|
+
: null;
|
|
244
|
+
const looksLikeNestApplication = mainSource?.includes('@nestjs/core') || mainSource?.includes('NestFactory');
|
|
245
|
+
if (looksLikeNestApplication) {
|
|
246
|
+
throw new Error(`Project "${projectName}" looks like a NestJS application but is missing "${joinPathFragments(resolvedSourceRoot, 'app.module.ts')}". NestJS apps must wire TypeORM through TypeOrmModule in app.module.ts; bootstrap will not patch main.ts for NestJS apps.`);
|
|
247
|
+
}
|
|
248
|
+
return 'plain';
|
|
223
249
|
}
|
|
224
250
|
function patchAppModule(tree, projectRoot, sourceRoot) {
|
|
225
251
|
const resolvedSourceRoot = sourceRoot ?? joinPathFragments(projectRoot, 'src');
|
|
@@ -239,7 +265,7 @@ function patchAppModule(tree, projectRoot, sourceRoot) {
|
|
|
239
265
|
overwrite: true,
|
|
240
266
|
});
|
|
241
267
|
ensureImport(sourceFile, '@nestjs/typeorm', 'TypeOrmModule');
|
|
242
|
-
ensureImport(sourceFile, runtimeImportPath, '
|
|
268
|
+
ensureImport(sourceFile, runtimeImportPath, 'AppDataSource');
|
|
243
269
|
const moduleDecorator = sourceFile
|
|
244
270
|
.getDescendantsOfKind(SyntaxKind.Decorator)
|
|
245
271
|
.find((decorator) => decorator.getName() === 'Module');
|
|
@@ -258,25 +284,70 @@ function patchAppModule(tree, projectRoot, sourceRoot) {
|
|
|
258
284
|
moduleLiteral = callExpression.addArgument('{}');
|
|
259
285
|
}
|
|
260
286
|
const importsArray = ensureImportsArray(moduleLiteral);
|
|
261
|
-
const
|
|
287
|
+
const existingTypeOrmRegistration = importsArray
|
|
262
288
|
.getElements()
|
|
263
|
-
.
|
|
264
|
-
if (
|
|
289
|
+
.find((element) => element.getText().includes('TypeOrmModule.forRoot'));
|
|
290
|
+
if (existingTypeOrmRegistration) {
|
|
291
|
+
existingTypeOrmRegistration.replaceWithText((writer) => {
|
|
292
|
+
writeNestTypeOrmRegistration(writer);
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
265
296
|
importsArray.addElement((writer) => {
|
|
266
|
-
writer
|
|
297
|
+
writeNestTypeOrmRegistration(writer);
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
tree.write(modulePath, sourceFile.getFullText());
|
|
301
|
+
}
|
|
302
|
+
function writeNestTypeOrmRegistration(writer) {
|
|
303
|
+
writer.write('TypeOrmModule.forRootAsync({');
|
|
304
|
+
writer.indent(() => {
|
|
305
|
+
writer.writeLine('useFactory: async () => ({');
|
|
306
|
+
writer.indent(() => {
|
|
307
|
+
writer.writeLine('...AppDataSource.options,');
|
|
308
|
+
writer.writeLine('autoLoadEntities: true,');
|
|
309
|
+
});
|
|
310
|
+
writer.writeLine('}),');
|
|
311
|
+
});
|
|
312
|
+
writer.write('})');
|
|
313
|
+
}
|
|
314
|
+
function patchMainFile(tree, projectRoot, sourceRoot) {
|
|
315
|
+
const resolvedSourceRoot = sourceRoot ?? joinPathFragments(projectRoot, 'src');
|
|
316
|
+
const mainPath = joinPathFragments(resolvedSourceRoot, 'main.ts');
|
|
317
|
+
if (!tree.exists(mainPath)) {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const sourceText = tree.read(mainPath, 'utf-8');
|
|
321
|
+
if (!sourceText) {
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const project = new Project({
|
|
325
|
+
useInMemoryFileSystem: true,
|
|
326
|
+
skipAddingFilesFromTsConfig: true,
|
|
327
|
+
});
|
|
328
|
+
const sourceFile = project.createSourceFile(mainPath, sourceText, {
|
|
329
|
+
overwrite: true,
|
|
330
|
+
});
|
|
331
|
+
ensureImport(sourceFile, './typeorm.datasource', 'AppDataSource');
|
|
332
|
+
const hasDataSourceInit = sourceFile
|
|
333
|
+
.getDescendantsOfKind(SyntaxKind.CallExpression)
|
|
334
|
+
.some((callExpression) => callExpression.getExpression().getText() === 'AppDataSource.initialize');
|
|
335
|
+
if (!hasDataSourceInit) {
|
|
336
|
+
const importDeclarations = sourceFile.getImportDeclarations();
|
|
337
|
+
const insertionIndex = importDeclarations.length > 0
|
|
338
|
+
? importDeclarations[importDeclarations.length - 1].getChildIndex() + 1
|
|
339
|
+
: 0;
|
|
340
|
+
sourceFile.insertStatements(insertionIndex, (writer) => {
|
|
341
|
+
writer.writeLine('');
|
|
342
|
+
writer.writeLine('void AppDataSource.initialize().catch((error) => {');
|
|
267
343
|
writer.indent(() => {
|
|
268
|
-
writer.writeLine('
|
|
269
|
-
writer.
|
|
270
|
-
writer.writeLine('...makeRuntimeDataSource().options,');
|
|
271
|
-
writer.writeLine('autoLoadEntities: true,');
|
|
272
|
-
});
|
|
273
|
-
writer.writeLine('}),');
|
|
274
|
-
writer.writeLine('dataSourceFactory: async () => makeRuntimeDataSource().initialize(),');
|
|
344
|
+
writer.writeLine("console.error('Failed to initialize TypeORM data source', error);");
|
|
345
|
+
writer.writeLine('process.exit(1);');
|
|
275
346
|
});
|
|
276
|
-
writer.
|
|
347
|
+
writer.writeLine('});');
|
|
277
348
|
});
|
|
278
349
|
}
|
|
279
|
-
tree.write(
|
|
350
|
+
tree.write(mainPath, sourceFile.getFullText());
|
|
280
351
|
}
|
|
281
352
|
function ensureImport(sourceFile, moduleSpecifier, importName) {
|
|
282
353
|
const existing = sourceFile.getImportDeclaration(moduleSpecifier);
|
|
@@ -35,6 +35,11 @@
|
|
|
35
35
|
"description": "Include a Docker Compose file for local Postgres development.",
|
|
36
36
|
"default": false
|
|
37
37
|
},
|
|
38
|
+
"migrationDatasource": {
|
|
39
|
+
"type": "boolean",
|
|
40
|
+
"description": "Create a separate migration datasource file for CLI commands.",
|
|
41
|
+
"default": false
|
|
42
|
+
},
|
|
38
43
|
"skipInstall": {
|
|
39
44
|
"type": "boolean",
|
|
40
45
|
"description": "Skip running package installations after updating dependencies.",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/entity-create/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/entity-create/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAKpB,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAE/D,wBAA8B,qBAAqB,CACjD,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,2BAA2B,iBA+BrC"}
|
|
@@ -1,21 +1,32 @@
|
|
|
1
1
|
import { joinPathFragments, readProjectConfiguration, } from '@nx/devkit';
|
|
2
|
-
import {
|
|
2
|
+
import { existsSync, renameSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, join, posix } from 'node:path';
|
|
3
4
|
import createEntity from '../../executors/entity-create/executor.js';
|
|
4
|
-
import { normalizeName } from '../../utils/shared.js';
|
|
5
|
+
import { normalizeName, toPascalCase } from '../../utils/shared.js';
|
|
5
6
|
export default async function entityCreateGenerator(tree, options) {
|
|
6
7
|
const projectName = requireOption(options.project, 'project');
|
|
7
|
-
const
|
|
8
|
+
const kebabName = normalizeName(requireOption(options.name, 'name'));
|
|
9
|
+
const classBaseName = ensureSuffix(toPascalCase(kebabName), 'Entity');
|
|
8
10
|
const projectConfig = readProjectConfiguration(tree, projectName);
|
|
9
11
|
const targetDirectory = resolveTargetDirectory(projectConfig.projectType, options.directory);
|
|
10
12
|
const context = createExecutorContext(tree, projectName);
|
|
11
13
|
const result = await createEntity({
|
|
12
14
|
projectRoot: projectConfig.root,
|
|
13
|
-
path: joinPathFragments(targetDirectory,
|
|
15
|
+
path: joinPathFragments(targetDirectory, classBaseName),
|
|
14
16
|
args: options.args,
|
|
15
17
|
}, context);
|
|
16
18
|
if (!result.success) {
|
|
17
19
|
throw new Error('TypeORM entity:create failed.');
|
|
18
20
|
}
|
|
21
|
+
const absDir = join(tree.root, projectConfig.root, targetDirectory);
|
|
22
|
+
const generatedFile = join(absDir, `${classBaseName}.ts`);
|
|
23
|
+
const expectedFile = join(absDir, `${kebabName}.entity.ts`);
|
|
24
|
+
if (existsSync(generatedFile)) {
|
|
25
|
+
renameSync(generatedFile, expectedFile);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function ensureSuffix(value, suffix) {
|
|
29
|
+
return value.endsWith(suffix) ? value : `${value}${suffix}`;
|
|
19
30
|
}
|
|
20
31
|
function resolveTargetDirectory(projectType, directory) {
|
|
21
32
|
if (!directory) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/subscriber-create/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"generator.d.ts","sourceRoot":"","sources":["../../../src/generators/subscriber-create/generator.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAKpB,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,aAAa,CAAC;AAEnE,wBAA8B,yBAAyB,CACrD,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,+BAA+B,iBA+BzC"}
|
|
@@ -1,21 +1,32 @@
|
|
|
1
1
|
import { joinPathFragments, readProjectConfiguration, } from '@nx/devkit';
|
|
2
|
-
import {
|
|
2
|
+
import { existsSync, renameSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, join, posix } from 'node:path';
|
|
3
4
|
import createSubscriber from '../../executors/subscriber-create/executor.js';
|
|
4
|
-
import { normalizeName } from '../../utils/shared.js';
|
|
5
|
+
import { normalizeName, toPascalCase } from '../../utils/shared.js';
|
|
5
6
|
export default async function subscriberCreateGenerator(tree, options) {
|
|
6
7
|
const projectName = requireOption(options.project, 'project');
|
|
7
|
-
const
|
|
8
|
+
const kebabName = normalizeName(requireOption(options.name, 'name'));
|
|
9
|
+
const classBaseName = ensureSuffix(toPascalCase(kebabName), 'Subscriber');
|
|
8
10
|
const projectConfig = readProjectConfiguration(tree, projectName);
|
|
9
11
|
const targetDirectory = resolveTargetDirectory(projectConfig.projectType, options.directory);
|
|
10
12
|
const context = createExecutorContext(tree, projectName);
|
|
11
13
|
const result = await createSubscriber({
|
|
12
14
|
projectRoot: projectConfig.root,
|
|
13
|
-
path: joinPathFragments(targetDirectory,
|
|
15
|
+
path: joinPathFragments(targetDirectory, classBaseName),
|
|
14
16
|
args: options.args,
|
|
15
17
|
}, context);
|
|
16
18
|
if (!result.success) {
|
|
17
19
|
throw new Error('TypeORM subscriber:create failed.');
|
|
18
20
|
}
|
|
21
|
+
const absDir = join(tree.root, projectConfig.root, targetDirectory);
|
|
22
|
+
const generatedFile = join(absDir, `${classBaseName}.ts`);
|
|
23
|
+
const expectedFile = join(absDir, `${kebabName}.subscriber.ts`);
|
|
24
|
+
if (existsSync(generatedFile)) {
|
|
25
|
+
renameSync(generatedFile, expectedFile);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function ensureSuffix(value, suffix) {
|
|
29
|
+
return value.endsWith(suffix) ? value : `${value}${suffix}`;
|
|
19
30
|
}
|
|
20
31
|
function resolveTargetDirectory(projectType, directory) {
|
|
21
32
|
if (!directory) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/plugin/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EAEd,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/plugin/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,aAAa,EAEd,MAAM,YAAY,CAAC;AAgUpB,eAAO,MAAM,aAAa,EAAE,aAgB3B,CAAC;AAEF,eAAO,MAAM,IAAI,uCAAuC,CAAC;;;;;AAEzD,wBAGE"}
|
package/dist/plugin/index.js
CHANGED
|
@@ -58,7 +58,7 @@ function inferDataSource(workspaceRoot, projectRoot, type) {
|
|
|
58
58
|
for (const candidate of candidates) {
|
|
59
59
|
const workspaceCandidate = join(workspaceRoot, projectRoot, candidate);
|
|
60
60
|
if (existsSync(workspaceCandidate)) {
|
|
61
|
-
return
|
|
61
|
+
return candidate;
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
return undefined;
|
|
@@ -124,6 +124,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
124
124
|
options: {
|
|
125
125
|
projectRoot,
|
|
126
126
|
dataSource: facts.dataSource,
|
|
127
|
+
moduleSystem: 'commonjs',
|
|
127
128
|
outputPath: facts.migrationsDirectory,
|
|
128
129
|
},
|
|
129
130
|
outputs: [facts.migrationsDirectory],
|
|
@@ -133,6 +134,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
133
134
|
options: {
|
|
134
135
|
projectRoot,
|
|
135
136
|
dataSource: facts.dataSource,
|
|
137
|
+
moduleSystem: 'commonjs',
|
|
136
138
|
},
|
|
137
139
|
};
|
|
138
140
|
targets['db:migrate:revert'] = {
|
|
@@ -140,6 +142,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
140
142
|
options: {
|
|
141
143
|
projectRoot,
|
|
142
144
|
dataSource: facts.dataSource,
|
|
145
|
+
moduleSystem: 'commonjs',
|
|
143
146
|
},
|
|
144
147
|
};
|
|
145
148
|
targets['db:migrate:show'] = {
|
|
@@ -147,6 +150,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
147
150
|
options: {
|
|
148
151
|
projectRoot,
|
|
149
152
|
dataSource: facts.dataSource,
|
|
153
|
+
moduleSystem: 'commonjs',
|
|
150
154
|
},
|
|
151
155
|
};
|
|
152
156
|
targets['db:schema:sync'] = {
|
|
@@ -154,6 +158,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
154
158
|
options: {
|
|
155
159
|
projectRoot,
|
|
156
160
|
dataSource: facts.dataSource,
|
|
161
|
+
moduleSystem: 'commonjs',
|
|
157
162
|
},
|
|
158
163
|
};
|
|
159
164
|
targets['db:schema:log'] = {
|
|
@@ -161,6 +166,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
161
166
|
options: {
|
|
162
167
|
projectRoot,
|
|
163
168
|
dataSource: facts.dataSource,
|
|
169
|
+
moduleSystem: 'commonjs',
|
|
164
170
|
},
|
|
165
171
|
};
|
|
166
172
|
targets['db:cache:clear'] = {
|
|
@@ -168,6 +174,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
168
174
|
options: {
|
|
169
175
|
projectRoot,
|
|
170
176
|
dataSource: facts.dataSource,
|
|
177
|
+
moduleSystem: 'commonjs',
|
|
171
178
|
},
|
|
172
179
|
};
|
|
173
180
|
targets['typeorm:generate'] = cloneTarget(targets['db:migrate:generate']);
|
|
@@ -184,6 +191,7 @@ function createTargets(projectRoot, type, facts) {
|
|
|
184
191
|
projectRoot,
|
|
185
192
|
schema: facts.schema,
|
|
186
193
|
dataSource: facts.dataSource,
|
|
194
|
+
moduleSystem: 'commonjs',
|
|
187
195
|
},
|
|
188
196
|
};
|
|
189
197
|
targets['typeorm:ensure-schema'] = cloneTarget(targets['db:ensure-schema']);
|
package/dist/utils/shared.d.ts
CHANGED
|
@@ -24,5 +24,6 @@ export declare function projectTypeFor(context: ExecutorContext): 'application'
|
|
|
24
24
|
export declare function schemaFilePath(projectRoot: string): string;
|
|
25
25
|
export declare function schemaNameFrom(contents: string): string | undefined;
|
|
26
26
|
export declare function normalizeName(name: string): string;
|
|
27
|
+
export declare function toPascalCase(name: string): string;
|
|
27
28
|
export {};
|
|
28
29
|
//# sourceMappingURL=shared.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/utils/shared.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAwB,MAAM,YAAY,CAAC;AAExE,KAAK,YAAY,GAAG,MAAM,GAAG,UAAU,GAAG,KAAK,CAAC;AAChD,KAAK,gBAAgB,GAAG,0BAA0B,GAAG,qBAAqB,CAAC;AAE3E,KAAK,4BAA4B,GAAG;IAClC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC;AAEF,KAAK,oBAAoB,GAAG;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AA0BF,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,eAAe,GACvB,oBAAoB,CAStB;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,OAAO,EAAE,eAAe,EACxB,mBAAmB,EAAE,MAAM,GAC1B,gBAAgB,CAWlB;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;AA4SD,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,aAAa,GAAG,SAAS,GAAG,SAAS,GACjD,MAAM,CAMR;AAED,wBAAgB,cAAc,CAC5B,OAAO,EAAE,eAAe,GACvB,aAAa,GAAG,SAAS,GAAG,SAAS,CAKvC;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"}
|
|
1
|
+
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/utils/shared.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAwB,MAAM,YAAY,CAAC;AAExE,KAAK,YAAY,GAAG,MAAM,GAAG,UAAU,GAAG,KAAK,CAAC;AAChD,KAAK,gBAAgB,GAAG,0BAA0B,GAAG,qBAAqB,CAAC;AAE3E,KAAK,4BAA4B,GAAG;IAClC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B,CAAC;AAEF,KAAK,oBAAoB,GAAG;IAC1B,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AA0BF,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,eAAe,GACvB,oBAAoB,CAStB;AAED,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,OAAO,EAAE,eAAe,EACxB,mBAAmB,EAAE,MAAM,GAC1B,gBAAgB,CAWlB;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;AA4SD,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,aAAa,GAAG,SAAS,GAAG,SAAS,GACjD,MAAM,CAMR;AAED,wBAAgB,cAAc,CAC5B,OAAO,EAAE,eAAe,GACvB,aAAa,GAAG,SAAS,GAAG,SAAS,CAKvC;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;AAED,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKjD"}
|
package/dist/utils/shared.js
CHANGED
|
@@ -258,3 +258,9 @@ export function schemaNameFrom(contents) {
|
|
|
258
258
|
export function normalizeName(name) {
|
|
259
259
|
return name.replace(/\s+/g, '-');
|
|
260
260
|
}
|
|
261
|
+
export function toPascalCase(name) {
|
|
262
|
+
return name
|
|
263
|
+
.split('-')
|
|
264
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
265
|
+
.join('');
|
|
266
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anarchitects/nx-typeorm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "Nx plugin providing TypeORM executors, generators, and schema management utilities.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -62,14 +62,11 @@
|
|
|
62
62
|
},
|
|
63
63
|
"peerDependencies": {
|
|
64
64
|
"@nx/devkit": ">= 19 < 23",
|
|
65
|
-
"ts-morph": "^22.0.0",
|
|
66
65
|
"ts-node": "^10.9.1",
|
|
67
|
-
"typeorm": "^0.3.
|
|
66
|
+
"typeorm": "^0.3.28"
|
|
68
67
|
},
|
|
69
68
|
"dependencies": {
|
|
69
|
+
"ts-morph": "^22.0.0",
|
|
70
70
|
"tslib": "^2.8.1"
|
|
71
|
-
},
|
|
72
|
-
"devDependencies": {
|
|
73
|
-
"ts-morph": "^22.0.0"
|
|
74
71
|
}
|
|
75
72
|
}
|
|
@@ -1,292 +0,0 @@
|
|
|
1
|
-
import type { DataSourceOptions } from 'typeorm';
|
|
2
|
-
|
|
3
|
-
type ConnectionMode = 'url' | 'fields';
|
|
4
|
-
|
|
5
|
-
const DATABASE_URL_KEY = 'DATABASE_URL';
|
|
6
|
-
const URL_OR_FIELDS_ERROR =
|
|
7
|
-
'Invalid TypeORM connection configuration. Provide either DATABASE_URL or TYPEORM_* variables, not both.';
|
|
8
|
-
const TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']);
|
|
9
|
-
const FALSE_VALUES = new Set(['0', 'false', 'no', 'off']);
|
|
10
|
-
<% if (database === 'postgres') { %>const DISCRETE_ENV_KEYS = [
|
|
11
|
-
'TYPEORM_HOST',
|
|
12
|
-
'TYPEORM_PORT',
|
|
13
|
-
'TYPEORM_USERNAME',
|
|
14
|
-
'TYPEORM_PASSWORD',
|
|
15
|
-
'TYPEORM_DATABASE',
|
|
16
|
-
'TYPEORM_SCHEMA',
|
|
17
|
-
'TYPEORM_SSL',
|
|
18
|
-
'TYPEORM_APPLICATION_NAME',
|
|
19
|
-
'TYPEORM_CONNECT_TIMEOUT_MS',
|
|
20
|
-
] as const;
|
|
21
|
-
|
|
22
|
-
type DatabaseConnectionOptions = Extract<DataSourceOptions, { type: 'postgres' }>;
|
|
23
|
-
<% } %><% if (database === 'mysql' || database === 'mariadb') { %>const DISCRETE_ENV_KEYS = [
|
|
24
|
-
'TYPEORM_HOST',
|
|
25
|
-
'TYPEORM_PORT',
|
|
26
|
-
'TYPEORM_USERNAME',
|
|
27
|
-
'TYPEORM_PASSWORD',
|
|
28
|
-
'TYPEORM_DATABASE',
|
|
29
|
-
'TYPEORM_SSL',
|
|
30
|
-
'TYPEORM_SOCKET_PATH',
|
|
31
|
-
'TYPEORM_CHARSET',
|
|
32
|
-
'TYPEORM_TIMEZONE',
|
|
33
|
-
'TYPEORM_CONNECT_TIMEOUT',
|
|
34
|
-
] as const;
|
|
35
|
-
|
|
36
|
-
type DatabaseConnectionOptions = Extract<DataSourceOptions, { type: '<%= database %>' }>;
|
|
37
|
-
<% } %><% if (database === 'mssql') { %>const DISCRETE_ENV_KEYS = [
|
|
38
|
-
'TYPEORM_HOST',
|
|
39
|
-
'TYPEORM_PORT',
|
|
40
|
-
'TYPEORM_USERNAME',
|
|
41
|
-
'TYPEORM_PASSWORD',
|
|
42
|
-
'TYPEORM_DATABASE',
|
|
43
|
-
'TYPEORM_DOMAIN',
|
|
44
|
-
'TYPEORM_CONNECTION_TIMEOUT',
|
|
45
|
-
'TYPEORM_REQUEST_TIMEOUT',
|
|
46
|
-
'TYPEORM_ENCRYPT',
|
|
47
|
-
'TYPEORM_TRUST_SERVER_CERTIFICATE',
|
|
48
|
-
'TYPEORM_INSTANCE_NAME',
|
|
49
|
-
] as const;
|
|
50
|
-
|
|
51
|
-
type DatabaseConnectionOptions = Extract<DataSourceOptions, { type: 'mssql' }>;
|
|
52
|
-
<% } %><% if (database === 'sqlite') { %>const DISCRETE_ENV_KEYS = [
|
|
53
|
-
'TYPEORM_DATABASE',
|
|
54
|
-
'TYPEORM_BUSY_TIMEOUT',
|
|
55
|
-
'TYPEORM_ENABLE_WAL',
|
|
56
|
-
] as const;
|
|
57
|
-
|
|
58
|
-
type DatabaseConnectionOptions = Extract<DataSourceOptions, { type: 'sqlite' }>;
|
|
59
|
-
<% } %><% if (database === 'better-sqlite3') { %>const DISCRETE_ENV_KEYS = [
|
|
60
|
-
'TYPEORM_DATABASE',
|
|
61
|
-
'TYPEORM_ENABLE_WAL',
|
|
62
|
-
'TYPEORM_TIMEOUT',
|
|
63
|
-
'TYPEORM_READONLY',
|
|
64
|
-
'TYPEORM_FILE_MUST_EXIST',
|
|
65
|
-
'TYPEORM_STATEMENT_CACHE_SIZE',
|
|
66
|
-
] as const;
|
|
67
|
-
|
|
68
|
-
type DatabaseConnectionOptions = Extract<DataSourceOptions, { type: 'better-sqlite3' }>;
|
|
69
|
-
<% } %>
|
|
70
|
-
|
|
71
|
-
export function createRuntimeDataSourceOptions(): DataSourceOptions {
|
|
72
|
-
return {
|
|
73
|
-
...createConnectionOptions(),
|
|
74
|
-
synchronize: false,
|
|
75
|
-
logging: false,
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export function createMigrationDataSourceOptions(): DataSourceOptions {
|
|
80
|
-
return {
|
|
81
|
-
...createConnectionOptions(),
|
|
82
|
-
entities: [],
|
|
83
|
-
migrations: ['dist/tools/typeorm/migrations/*.js'],
|
|
84
|
-
synchronize: false,
|
|
85
|
-
logging: false,
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
function createConnectionOptions(): DatabaseConnectionOptions {
|
|
90
|
-
return resolveConnectionMode() === 'url'
|
|
91
|
-
? createOptionsFromUrl()
|
|
92
|
-
: createOptionsFromFields();
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function resolveConnectionMode(): ConnectionMode {
|
|
96
|
-
const hasDatabaseUrl = optionalEnv(DATABASE_URL_KEY) !== undefined;
|
|
97
|
-
const hasDiscreteVariables = DISCRETE_ENV_KEYS.some(
|
|
98
|
-
(key) => optionalEnv(key) !== undefined
|
|
99
|
-
);
|
|
100
|
-
|
|
101
|
-
if (hasDatabaseUrl && hasDiscreteVariables) {
|
|
102
|
-
throw new Error(URL_OR_FIELDS_ERROR);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return hasDatabaseUrl ? 'url' : 'fields';
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function requiredEnv(name: string): string {
|
|
109
|
-
const value = optionalEnv(name);
|
|
110
|
-
if (!value) {
|
|
111
|
-
throw new Error(`Missing required environment variable "${name}".`);
|
|
112
|
-
}
|
|
113
|
-
return value;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
function optionalEnv(name: string): string | undefined {
|
|
117
|
-
const value = process.env[name];
|
|
118
|
-
if (!value) {
|
|
119
|
-
return undefined;
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const trimmed = value.trim();
|
|
123
|
-
return trimmed.length > 0 ? trimmed : undefined;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
function parseBooleanEnv(name: string): boolean | undefined {
|
|
127
|
-
const value = optionalEnv(name);
|
|
128
|
-
if (value === undefined) {
|
|
129
|
-
return undefined;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const normalized = value.toLowerCase();
|
|
133
|
-
if (TRUE_VALUES.has(normalized)) {
|
|
134
|
-
return true;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
if (FALSE_VALUES.has(normalized)) {
|
|
138
|
-
return false;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
throw new Error(
|
|
142
|
-
`Environment variable "${name}" must be a boolean value (true/false/1/0/yes/no/on/off).`
|
|
143
|
-
);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function parseIntegerEnv(name: string): number | undefined {
|
|
147
|
-
const value = optionalEnv(name);
|
|
148
|
-
if (value === undefined) {
|
|
149
|
-
return undefined;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
if (!/^-?\d+$/.test(value)) {
|
|
153
|
-
throw new Error(`Environment variable "${name}" must be an integer.`);
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
const parsed = Number.parseInt(value, 10);
|
|
157
|
-
if (!Number.isSafeInteger(parsed)) {
|
|
158
|
-
throw new Error(`Environment variable "${name}" must be an integer.`);
|
|
159
|
-
}
|
|
160
|
-
return parsed;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
function parseSslEnv(name: string): boolean | Record<string, unknown> | undefined {
|
|
164
|
-
const value = optionalEnv(name);
|
|
165
|
-
if (value === undefined) {
|
|
166
|
-
return undefined;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
const normalized = value.toLowerCase();
|
|
170
|
-
if (TRUE_VALUES.has(normalized)) {
|
|
171
|
-
return true;
|
|
172
|
-
}
|
|
173
|
-
if (FALSE_VALUES.has(normalized)) {
|
|
174
|
-
return false;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
try {
|
|
178
|
-
const parsed = JSON.parse(value) as unknown;
|
|
179
|
-
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
180
|
-
return parsed as Record<string, unknown>;
|
|
181
|
-
}
|
|
182
|
-
} catch {
|
|
183
|
-
// Ignore and throw below with context.
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
throw new Error(
|
|
187
|
-
`Environment variable "${name}" must be a boolean or a JSON object.`
|
|
188
|
-
);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
<% if (database === 'postgres') { %>function createOptionsFromUrl(): DatabaseConnectionOptions {
|
|
192
|
-
return {
|
|
193
|
-
type: 'postgres',
|
|
194
|
-
url: requiredEnv(DATABASE_URL_KEY),
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function createOptionsFromFields(): DatabaseConnectionOptions {
|
|
199
|
-
return {
|
|
200
|
-
type: 'postgres',
|
|
201
|
-
host: requiredEnv('TYPEORM_HOST'),
|
|
202
|
-
port: parseIntegerEnv('TYPEORM_PORT') ?? 5432,
|
|
203
|
-
username: requiredEnv('TYPEORM_USERNAME'),
|
|
204
|
-
password: requiredEnv('TYPEORM_PASSWORD'),
|
|
205
|
-
database: requiredEnv('TYPEORM_DATABASE'),
|
|
206
|
-
schema: optionalEnv('TYPEORM_SCHEMA'),
|
|
207
|
-
ssl: parseSslEnv('TYPEORM_SSL'),
|
|
208
|
-
applicationName: optionalEnv('TYPEORM_APPLICATION_NAME'),
|
|
209
|
-
connectTimeoutMS: parseIntegerEnv('TYPEORM_CONNECT_TIMEOUT_MS'),
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
<% } %><% if (database === 'mysql' || database === 'mariadb') { %>function createOptionsFromUrl(): DatabaseConnectionOptions {
|
|
213
|
-
return {
|
|
214
|
-
type: '<%= database %>',
|
|
215
|
-
url: requiredEnv(DATABASE_URL_KEY),
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function createOptionsFromFields(): DatabaseConnectionOptions {
|
|
220
|
-
return {
|
|
221
|
-
type: '<%= database %>',
|
|
222
|
-
host: requiredEnv('TYPEORM_HOST'),
|
|
223
|
-
port: parseIntegerEnv('TYPEORM_PORT') ?? 3306,
|
|
224
|
-
username: requiredEnv('TYPEORM_USERNAME'),
|
|
225
|
-
password: requiredEnv('TYPEORM_PASSWORD'),
|
|
226
|
-
database: requiredEnv('TYPEORM_DATABASE'),
|
|
227
|
-
ssl: parseSslEnv('TYPEORM_SSL'),
|
|
228
|
-
socketPath: optionalEnv('TYPEORM_SOCKET_PATH'),
|
|
229
|
-
charset: optionalEnv('TYPEORM_CHARSET'),
|
|
230
|
-
timezone: optionalEnv('TYPEORM_TIMEZONE'),
|
|
231
|
-
connectTimeout: parseIntegerEnv('TYPEORM_CONNECT_TIMEOUT'),
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
<% } %><% if (database === 'mssql') { %>function createOptionsFromUrl(): DatabaseConnectionOptions {
|
|
235
|
-
return {
|
|
236
|
-
type: 'mssql',
|
|
237
|
-
url: requiredEnv(DATABASE_URL_KEY),
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function createOptionsFromFields(): DatabaseConnectionOptions {
|
|
242
|
-
return {
|
|
243
|
-
type: 'mssql',
|
|
244
|
-
host: requiredEnv('TYPEORM_HOST'),
|
|
245
|
-
port: parseIntegerEnv('TYPEORM_PORT') ?? 1433,
|
|
246
|
-
username: requiredEnv('TYPEORM_USERNAME'),
|
|
247
|
-
password: requiredEnv('TYPEORM_PASSWORD'),
|
|
248
|
-
database: requiredEnv('TYPEORM_DATABASE'),
|
|
249
|
-
domain: optionalEnv('TYPEORM_DOMAIN'),
|
|
250
|
-
connectionTimeout: parseIntegerEnv('TYPEORM_CONNECTION_TIMEOUT'),
|
|
251
|
-
requestTimeout: parseIntegerEnv('TYPEORM_REQUEST_TIMEOUT'),
|
|
252
|
-
options: {
|
|
253
|
-
encrypt: parseBooleanEnv('TYPEORM_ENCRYPT'),
|
|
254
|
-
trustServerCertificate: parseBooleanEnv('TYPEORM_TRUST_SERVER_CERTIFICATE'),
|
|
255
|
-
instanceName: optionalEnv('TYPEORM_INSTANCE_NAME'),
|
|
256
|
-
},
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
<% } %><% if (database === 'sqlite') { %>function createOptionsFromUrl(): DatabaseConnectionOptions {
|
|
260
|
-
return {
|
|
261
|
-
type: 'sqlite',
|
|
262
|
-
database: requiredEnv(DATABASE_URL_KEY),
|
|
263
|
-
};
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
function createOptionsFromFields(): DatabaseConnectionOptions {
|
|
267
|
-
return {
|
|
268
|
-
type: 'sqlite',
|
|
269
|
-
database: requiredEnv('TYPEORM_DATABASE'),
|
|
270
|
-
busyTimeout: parseIntegerEnv('TYPEORM_BUSY_TIMEOUT'),
|
|
271
|
-
enableWAL: parseBooleanEnv('TYPEORM_ENABLE_WAL'),
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
<% } %><% if (database === 'better-sqlite3') { %>function createOptionsFromUrl(): DatabaseConnectionOptions {
|
|
275
|
-
return {
|
|
276
|
-
type: 'better-sqlite3',
|
|
277
|
-
database: requiredEnv(DATABASE_URL_KEY),
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
function createOptionsFromFields(): DatabaseConnectionOptions {
|
|
282
|
-
return {
|
|
283
|
-
type: 'better-sqlite3',
|
|
284
|
-
database: requiredEnv('TYPEORM_DATABASE'),
|
|
285
|
-
enableWAL: parseBooleanEnv('TYPEORM_ENABLE_WAL'),
|
|
286
|
-
timeout: parseIntegerEnv('TYPEORM_TIMEOUT'),
|
|
287
|
-
readonly: parseBooleanEnv('TYPEORM_READONLY'),
|
|
288
|
-
fileMustExist: parseBooleanEnv('TYPEORM_FILE_MUST_EXIST'),
|
|
289
|
-
statementCacheSize: parseIntegerEnv('TYPEORM_STATEMENT_CACHE_SIZE'),
|
|
290
|
-
};
|
|
291
|
-
}
|
|
292
|
-
<% } %>
|