Skip to content

Commit

Permalink
🚸 Improve config override function
Browse files Browse the repository at this point in the history
  • Loading branch information
skgndi12 committed Apr 20, 2023
1 parent 6addef2 commit 12ee3f6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
36 changes: 27 additions & 9 deletions api/src/config/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,36 @@ interface HttpConfig {
port: number;
}

export function load(path: string): Config {
export function load(): convict.Config<ServerConfig> {
try {
envLoad();
const config = jsYaml.load(readFileSync(path, 'utf-8')) as Config;
return {
env: process.env.ENV ? process.env.ENV : config.env,
server: {
host: process.env.HOST ? process.env.HOST : config.server.host,
port: process.env.PORT ? process.env.PORT : config.server.port
convict.addFormats(convict_format_with_validator);
convict.addParser({ extension: ['yml', 'yaml'], parse: yaml.load });
const config = convict({
env: {
doc: 'The Mr.C API application environment.',
format: ['production', 'development', 'test', 'local'],
default: 'local',
env: 'MRC_API_ENV'
},
http: {
host: {
doc: 'The host address to bind',
format: 'ipaddress',
default: '127.0.0.1',
env: 'MRC_API_HOST'
},
port: {
doc: 'The port to bind',
format: 'port',
default: 8080,
env: 'MRC_API_PORT'
}
}
};
});
config.loadFile(String(process.env.MRC_API_CONFIG_DIR));
return config;
} catch (e) {
throw new Error('failed to load config');
throw new Error(`failed to load config error: ${e}`);
}
}
7 changes: 3 additions & 4 deletions api/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { load } from './config/loader';

function main() {
const configPath = './src/config/default.yaml';
try {
const config = load(configPath);
console.log(config);
const config = load();
console.log(config.get());
} catch (e) {
if (e instanceof Error) {
console.error(`error: ${e.message}`);
console.error(`${e.message}`);
}
}
}
Expand Down

0 comments on commit 12ee3f6

Please sign in to comment.