feat(web): T-WEB-001 NestJS 骨架 + 连接现有 MySQL 实例
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import 'reflect-metadata';
|
||||
import { config as loadEnv } from 'dotenv';
|
||||
import { join } from 'node:path';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { MysqlConnectionOptions } from 'typeorm/driver/mysql/MysqlConnectionOptions';
|
||||
import { ENTITIES } from '../entities';
|
||||
|
||||
// CLI(typeorm-ts-node-commonjs)与 Nest 运行期都从这里读环境变量
|
||||
loadEnv();
|
||||
|
||||
function bool(value: string | undefined, fallback = false): boolean {
|
||||
if (value === undefined || value === '') return fallback;
|
||||
return value === 'true' || value === '1';
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接「现有 MySQL 实例」——本项目不部署、不管理 MySQL。
|
||||
* 契约 contracts/database.md。
|
||||
*
|
||||
* 返回 MySQL 驱动选项的具体类型(而非 DataSourceOptions 联合类型),
|
||||
* 以便 AppModule 中安全地做字段覆盖。
|
||||
*/
|
||||
export function buildDataSourceOptions(env: NodeJS.ProcessEnv = process.env): MysqlConnectionOptions {
|
||||
return {
|
||||
type: 'mysql',
|
||||
host: env.DB_HOST ?? '127.0.0.1',
|
||||
port: Number(env.DB_PORT ?? 3306),
|
||||
username: env.DB_USER ?? 'opendance_app',
|
||||
password: env.DB_PASS ?? '',
|
||||
database: env.DB_NAME ?? 'opendance',
|
||||
// 契约要求:生产环境禁止 synchronize,表结构一律走 migration
|
||||
synchronize: false,
|
||||
logging: bool(env.DB_LOGGING, false),
|
||||
entities: ENTITIES,
|
||||
migrations: [join(__dirname, '..', 'migrations', '*.{ts,js}')],
|
||||
migrationsTableName: 'typeorm_migrations',
|
||||
charset: 'utf8mb4',
|
||||
timezone: 'Z',
|
||||
// 让 BIGINT 在可精确表示时返回 number(契约中 id 为 number)
|
||||
supportBigNumbers: true,
|
||||
bigNumberStrings: false,
|
||||
extra: {
|
||||
connectionLimit: Number(env.DB_POOL_SIZE ?? 10),
|
||||
decimalNumbers: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const dataSourceOptions: MysqlConnectionOptions = buildDataSourceOptions();
|
||||
|
||||
/**
|
||||
* 注意:本文件必须只有 **一个** DataSource 实例导出(default),
|
||||
* 否则 typeorm CLI 会报 "must contain only one export of DataSource instance"。
|
||||
*/
|
||||
const AppDataSource = new DataSource(dataSourceOptions);
|
||||
|
||||
export default AppDataSource;
|
||||
Reference in New Issue
Block a user