made config async
This commit is contained in:
parent
92d4b90987
commit
caf1c5fcaf
6 changed files with 91 additions and 143 deletions
|
|
@ -1,4 +1,4 @@
|
|||
import { readFile } from 'fs/promises';
|
||||
import { readFileSync, existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { ConfigLoader } from '../types';
|
||||
import { ConfigLoaderError } from '../errors';
|
||||
|
|
@ -11,18 +11,18 @@ export class FileLoader implements ConfigLoader {
|
|||
private environment: string
|
||||
) {}
|
||||
|
||||
async load(): Promise<Record<string, unknown>> {
|
||||
load(): Record<string, unknown> {
|
||||
try {
|
||||
const configs: Record<string, unknown>[] = [];
|
||||
|
||||
// Load default config
|
||||
const defaultConfig = await this.loadFile('default.json');
|
||||
const defaultConfig = this.loadFile('default.json');
|
||||
if (defaultConfig) {
|
||||
configs.push(defaultConfig);
|
||||
}
|
||||
|
||||
// Load environment-specific config
|
||||
const envConfig = await this.loadFile(`${this.environment}.json`);
|
||||
const envConfig = this.loadFile(`${this.environment}.json`);
|
||||
if (envConfig) {
|
||||
configs.push(envConfig);
|
||||
}
|
||||
|
|
@ -37,30 +37,26 @@ export class FileLoader implements ConfigLoader {
|
|||
}
|
||||
}
|
||||
|
||||
private async loadFile(filename: string): Promise<Record<string, unknown> | null> {
|
||||
private loadFile(filename: string): Record<string, unknown> | null {
|
||||
const filepath = join(this.configPath, filename);
|
||||
|
||||
try {
|
||||
const content = await readFile(filepath, 'utf-8');
|
||||
return JSON.parse(content);
|
||||
} catch (error: unknown) {
|
||||
// File not found is not an error (configs are optional)
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
|
||||
if (!existsSync(filepath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = readFileSync(filepath, 'utf-8');
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
private deepMerge(...objects: Record<string, any>[]): Record<string, any> {
|
||||
const result: Record<string, any> = {};
|
||||
private deepMerge(...objects: Record<string, unknown>[]): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
for (const obj of objects) {
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
if (value === null || value === undefined) {
|
||||
result[key] = value;
|
||||
} else if (typeof value === 'object' && !Array.isArray(value)) {
|
||||
result[key] = this.deepMerge(result[key] || {}, value);
|
||||
} else if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
|
||||
result[key] = this.deepMerge(result[key] as Record<string, unknown> || {}, value as Record<string, unknown>);
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue