An open API service indexing awesome lists of open source software.

https://github.com/jondotsoy/life-config


https://github.com/jondotsoy/life-config

Last synced: 3 months ago
JSON representation

Awesome Lists containing this project

README

        

# life-config 🍃

Configuration on runtime.

**Example**

```ts
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

```shell
npm install life-config
```

## Data Source

A data source describe how to load the new configurations describe it on [source.ts](./src/dtos/source.ts).

The next sample subscribe changes on the source and connect it with [nanostores](https://github.com/nanostores/nanostores).

```ts
// 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.

```ts
const state = lifeConfig.state;

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

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

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

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

## File Source

A source to watch file and load on each change.

```ts
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.

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

## Subscriptor Source

```ts
import { atom } from "nanostores";

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

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