Skip to content

JonDotsoy/life-config

Repository files navigation

life-config 🍃

Configuration on runtime.

Example

const lifeConfig = await LifeConfig.create(
  new FileSource<{ prefixLog: string }>("config.json"),
);

let logPrefix: string;

await lifeConfig.subscribe((state) => (logPrefix = state.logPrefix));

console.log(`${logPrefix} hello 1`); // => [log] hello 1
// echo '{ "logPrefix": "super-log" }' > config.json
console.log(`${logPrefix} hello 2`); // => [super-log] hello 2

Install

npm install life-config

Data Source

A data source describe how to load the new configurations describe it on source.ts.

The next sample subscribe changes on the source and connect it with nanostores.

// config.ts
import { atom } from "nanostores";

export const logLevel = atom("info");
lifeConfig.subscribe((state) => logLevel.set(state.logLevel));

Connect variable

With LifeConfig.prototype.state.get() return the current state and break it if is not initialized the first state.

const state = lifeConfig.state;

state.get(); // => { "logLevel": "info" }

Also you can computed the state before to get it with LifeConfig.prototype.state.computed(fn).

const logLevel = lifeConfig.state.computed((state) => state.logLevel);

logLevel.get(); // => "info"

File Source

A source to watch file and load on each change.

const lifeConfig = await LifeConfig.create(new FileSource("my-file.json"));

HTTP Source

A source to refresh the state if detect changes from a http resources.

const lifeConfig = await LifeConfig.create(
  new HTTPSource("http://localhost/config"),
);

Subscriptor Source

import { atom } from "nanostores";

const config = atom({ logLevel: "info" });

const lifeConfig = await LifeConfig.create(new SubscriptorSource(config));