Files
gongxue-base/apps/server/datasource.ts
wangziqi f4072ce93a fix(db): 迁移 CLI 默认读取仓库根目录 .env
- datasource.ts 优先加载根目录 .env,再回退 apps/server/.env
- 生产只需维护根目录一份 .env,迁移脚本不再报 root 空密码
2026-08-09 22:02:00 +08:00

29 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { DataSource } from 'typeorm';
import { config } from 'dotenv';
import { basename, join, resolve } from 'path';
// TypeORM CLI 默认在 apps/server/ 下运行,但生产环境的 .env 通常放在仓库根目录。
// 这里先加载仓库根目录的 .env默认再加载当前目录apps/server/.env作为补充/覆盖,
// 这样无论 .env 放哪一份,迁移 CLI 都能读到数据库配置。
const root = resolve(process.cwd());
const repoRoot =
basename(root) === 'server' && basename(join(root, '..')) === 'apps'
? resolve(root, '../..')
: root;
// 先根目录后当前目录dotenv 默认不覆盖已存在变量,所以根目录优先级更高)
config({ path: join(repoRoot, '.env') });
config({ path: join(root, '.env') });
export default new DataSource({
type: 'mysql',
host: process.env.DB_HOST || 'localhost',
port: Number(process.env.DB_PORT) || 3306,
username: process.env.DB_USERNAME || 'root',
password: process.env.DB_PASSWORD || '',
database: process.env.DB_DATABASE || 'dorm_billing',
charset: 'utf8mb4',
entities: [join(root, 'src/**/*.entity.ts')],
migrations: [join(root, 'src/migrations/*.ts')],
});