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 can 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. Once initialized configurations can be reloaded without app restart.
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.getValues(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.getValues(Settings).someProperty)
config.log(Config.getValues(AnotherSettings).someProperty)
config.log(Config.getValues(MoreAnotherSettings).someProperty)
config.log(Config.getValues(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();
Todo before 1.0.0 release
- allow to automate configurations values reloads in user-defined source group scoped intervals
- add hook for config refreshed event to allow an app react to the change. Pass difference between old and new values?
- add example project under
/examples
directory
License
This project is licensed under the MIT License - see the LICENSE file for details.