| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import "reflect-metadata"
- import { DataSource, EntitySchema, MixedList } from "typeorm"
- import process from 'node:process'
- // 实体目标类型,可以是类、函数或实体模式
- export type EntityTarget = Function | EntitySchema<any> | string
- /**
- * 创建数据源配置
- * @param entities 实体类数组
- * @param migrations 迁移文件数组(可选),当传入此参数时(即使是空数组),非测试环境的 synchronize 自动为 false
- * @returns DataSource 实例
- */
- export function createDataSource(entities: EntityTarget[], migrations?: MixedList<string | Function>): DataSource {
- // 在测试环境下使用测试数据库配置
- const isTestEnv = process.env.NODE_ENV === 'test';
- const testDatabaseUrl = process.env.TEST_DATABASE_URL || 'postgresql://postgres:test_password@localhost:5432/test_d8dai';
- // 非测试环境的 synchronize 逻辑
- const shouldSynchronize = migrations !== undefined
- ? false // 传入了 migrations 参数(即使是空数组),synchronize 设为 false
- : process.env.DB_SYNCHRONIZE !== "false"; // 否则使用环境变量配置
- return isTestEnv && testDatabaseUrl
- ? new DataSource({
- type: "postgres",
- url: testDatabaseUrl,
- entities,
- migrations: [], // 测试环境忽略迁移文件
- synchronize: true, // 测试环境总是同步schema
- dropSchema: true, // 测试环境每次重新创建schema
- logging: false, // 测试环境关闭日志
- })
- : new DataSource({
- type: "postgres",
- host: process.env.DB_HOST || "localhost",
- port: parseInt(process.env.DB_PORT || "5432"),
- username: process.env.DB_USERNAME || "postgres",
- password: process.env.DB_PASSWORD || "",
- database: process.env.DB_DATABASE || "postgres",
- entities,
- migrations: migrations || [],
- synchronize: shouldSynchronize,
- logging: process.env.DB_LOGGING === "true",
- });
- }
- /**
- * 默认数据源实例(需要传入实体)
- * 注意:这个实例需要在具体模块中传入实体类
- */
- export let AppDataSource: DataSource;
- /**
- * 初始化默认数据源
- * @param entities 实体类数组
- * @param migrations 迁移文件数组(可选)
- */
- export function initializeDataSource(entities: EntityTarget[], migrations?: MixedList<string | Function>): void {
- AppDataSource = createDataSource(entities, migrations);
- }
|