Unifig
Table of contents
💡 Goal
Unifig aims to provides simple and abstract way of handling app's configuration. It allows to load configuration data from multiple sources without changing defined config template. Many templates an be defined to further organize the code eg. MainConfiguration and ModuleConfiguration.
Adapted configuration data is transformed into templates and validated via class-transformer and class-validator.
Installation
npm i @unifig/core
yarn add @unifig/core
Quick Start
import { From, Nested } from '@unifig/core';
import { Transform } from 'class-transformer';
import { IsString, IsArray } from 'class-validator';
class DbSettings {
@From('global.dbUrl')
@IsString()
url: string;
@From('global.dbPassword')
@IsString()
password: string;
}
export class Settings {
@From('local.port')
@IsInt()
port: number;
@Transform(({ value }) => value.split(',').map((n) => Number(n)))
@IsArray()
intervals: number[];
@Nested(DbSettings)
db: DbSettings;
}
import { Config, PlainConfigAdapter } from '@unifig/core';
async function bootstrap() {
await Config.register({
template: Settings,
adapter: new PlainConfigAdapter({
local: { port: 3000 },
global: { dbUrl: 'localhost:5467', dbPassword: 'password' },
intervals: '56,98,34,72',
}),
});
console.log(Config.values(Settings).port);
}
bootstrap();
Above example uses built-in adapter which transforms static object into Settings. See full list of adapters here.
Multiple Configurations
async function bootstrap() {
await Config.register(
{ template: Settings, adapter: ... },
{ template: AnotherSettings, adapter: ... },
{ templates: [MoreAnotherSettings, YetMoreAnotherSettings], adapter: ... },
);
config.log(Config.values(Settings).someProperty)
config.log(Config.values(AnotherSettings).someProperty)
config.log(Config.values(MoreAnotherSettings).someProperty)
config.log(Config.values(YetMoreAnotherSettings).someProperty)
}
Additional configs may be registered with separate .register()
calls.
Stale Data
Upon changing application's configuration one must be usually restared to re-fetch new values. Unifig delivers an option to reload registered configurations in real time without app's restart.
await Config.getContainer(Settings).refresh();
License
This project is licensed under the MIT License - see the LICENSE file for details.