| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import "reflect-metadata"
- import { DataSource, EntitySchema } from "typeorm"
- import process from 'node:process'
- // 实体目标类型,可以是类、函数或实体模式
- type EntityTarget = Function | EntitySchema<any> | string
- /**
- * 创建数据源配置
- * @param entities 实体类数组
- * @returns DataSource 实例
- */
- export function createDataSource(entities: EntityTarget<any>[]): DataSource {
- // 在测试环境下使用测试数据库配置
- const isTestEnv = process.env.NODE_ENV === 'test';
- const testDatabaseUrl = process.env.TEST_DATABASE_URL || 'postgresql://postgres:test_password@localhost:5432/test_d8dai';
- 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: [],
- synchronize: process.env.DB_SYNCHRONIZE !== "false",
- logging: process.env.DB_LOGGING === "true",
- });
- }
- /**
- * 默认数据源实例(需要传入实体)
- * 注意:这个实例需要在具体模块中传入实体类
- */
- export let AppDataSource: DataSource;
- /**
- * 初始化默认数据源
- * @param entities 实体类数组
- */
- export function initializeDataSource(entities: EntityTarget<any>[]): void {
- AppDataSource = createDataSource(entities);
- }
|