Files
certd/packages/ui/certd-server/src/config/loader.ts
T

60 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-06-26 12:26:59 +08:00
import path from 'path';
2024-07-15 00:30:33 +08:00
import * as _ from 'lodash-es';
import yaml from 'js-yaml';
import fs from 'fs';
2024-10-03 22:03:49 +08:00
import { logger } from '@certd/pipeline';
2023-06-26 12:26:59 +08:00
2023-07-03 13:42:48 +08:00
function parseEnv(defaultConfig: any) {
2023-06-26 12:26:59 +08:00
const config = {};
for (const key in process.env) {
let keyName = key;
if (!keyName.startsWith('certd_')) {
continue;
}
keyName = keyName.replace('certd_', '');
const configKey = keyName.replaceAll('_', '.');
2023-07-03 13:42:48 +08:00
const oldValue = _.get(defaultConfig, configKey);
let value: any = process.env[key];
if (typeof oldValue === 'boolean') {
value = value === 'true';
} else if (Number.isInteger(oldValue)) {
value = parseInt(value, 10);
} else if (typeof oldValue === 'number') {
value = parseFloat(value);
}
_.set(config, configKey, value);
2023-06-26 12:26:59 +08:00
}
return config;
}
2023-07-03 13:42:48 +08:00
export function load(config, env = '') {
2023-06-26 12:26:59 +08:00
// Get document, or throw exception on error
2024-07-17 01:30:00 +08:00
logger.info('load config', env);
2023-06-26 12:26:59 +08:00
const yamlPath = path.join(process.cwd(), `.env.${env}.yaml`);
2024-07-18 11:17:13 +08:00
if (fs.existsSync(yamlPath)) {
const doc = yaml.load(fs.readFileSync(yamlPath, 'utf8'));
return _.merge(doc, parseEnv(config));
}
return parseEnv(config);
2023-06-26 12:26:59 +08:00
}
2023-06-28 09:44:35 +08:00
export function mergeConfig(config: any, envType: string) {
2023-07-03 13:42:48 +08:00
_.merge(config, load(config, envType));
2023-06-28 09:44:35 +08:00
const keys = _.get(config, 'auth.jwt.secret');
if (keys) {
config.keys = keys;
}
return config;
}
2024-11-04 15:14:56 +08:00
export function loadDotEnv() {
const envStr = fs.readFileSync('.env').toString();
envStr.split('\n').forEach(line => {
const [key, value] = line.split('=');
const oldValue = process.env[key];
if (!oldValue) {
process.env[key] = value;
}
});
}