56 lines
1.7 KiB
TypeScript
56 lines
1.7 KiB
TypeScript
import { resolve } from 'path';
|
|
import { PrismaClient } from '@prisma/client';
|
|
import { normalizePemEnv } from '../../integrations/wechat/wechat-pay.util';
|
|
import { SYSTEM_CONFIG_KEY_SET } from './system-config.registry';
|
|
|
|
const PEM_ENV_KEYS = new Set(['WX_MCH_PRIVATE_KEY', 'WX_PLATFORM_CERT']);
|
|
|
|
function apiRoot() {
|
|
return resolve(__dirname, '..', '..');
|
|
}
|
|
|
|
export function resolveEnvFilePath() {
|
|
const isProduction = (process.env.NODE_ENV ?? 'development') === 'production';
|
|
return resolve(apiRoot(), isProduction ? '.env.production' : '.env');
|
|
}
|
|
|
|
function normalizeConfigValue(key: string, value: string): string {
|
|
if (PEM_ENV_KEYS.has(key)) return normalizePemEnv(value);
|
|
return value;
|
|
}
|
|
|
|
/** 启动前从 DB 覆盖 process.env(在 Nest 创建前调用) */
|
|
export async function preloadSystemConfigEnv(): Promise<number> {
|
|
const prisma = new PrismaClient();
|
|
try {
|
|
const rows = await prisma.systemConfig.findMany();
|
|
for (const row of rows) {
|
|
if (SYSTEM_CONFIG_KEY_SET.has(row.configKey)) {
|
|
process.env[row.configKey] = normalizeConfigValue(row.configKey, row.value);
|
|
}
|
|
}
|
|
return rows.length;
|
|
} catch (error) {
|
|
if (
|
|
typeof error === 'object' &&
|
|
error !== null &&
|
|
'code' in error &&
|
|
(error as { code?: string }).code === 'P2021'
|
|
) {
|
|
console.warn('[config] system_config 表不存在,跳过 DB 预加载');
|
|
return 0;
|
|
}
|
|
throw error;
|
|
} finally {
|
|
await prisma.$disconnect();
|
|
}
|
|
}
|
|
|
|
export function applyEnvOverlay(values: Record<string, string>) {
|
|
for (const [key, value] of Object.entries(values)) {
|
|
if (SYSTEM_CONFIG_KEY_SET.has(key)) {
|
|
process.env[key] = normalizeConfigValue(key, value);
|
|
}
|
|
}
|
|
}
|