Key/value pair configuration
Key/Value pair configuration library
The package is part of
@Sarina
framework
Install by yarn
yarn add @sarina/configuration
import { ConfigurationBuilder, MemoryConfigurationSource, EnvironmentConfigurationSource } from '@sarina/configuration';
const bootstrap = async () => {
const provider = await new ConfigurationBuilder()
.add(new MemoryConfigurationSource({ HOST: 'http://127.0.0.1', PORT: '3000' }))
.add(new EnvironmentConfigurationSource())
.build();
const host = provider.getAsString('HOST');
const port = provider.getAsString('PORT');
};
bootstrap()
.then()
.catch();
To check if value exists or not use has
method:
const provider = await new ConfigurationBuilder()
.add(new MemoryConfigurationSource({ HOST: 'http://127.0.0.1', PORT: '3000' }))
.build();
const isHostExists = provider.has("HOST");
// true
To check if value exists or not use has
method:
const provider = await new ConfigurationBuilder()
.add(new MemoryConfigurationSource({ HOST: 'http://127.0.0.1', PORT: '3000' }))
.build();
const isHostExists = provider.has("HOST");
// true
To get configuration element use get
method:
const provider = await new ConfigurationBuilder()
.add(new MemoryConfigurationSource({ HOST: 'http://127.0.0.1', PORT: '3000' }))
.build();
const config = provider.get("HOST");
const host = config.value;
Library supports nested configuration. The getScoped
method, will get a path
and returns an instance of IConfiguration
which contains all configuration methods scoped to the path
:
const provider = await new ConfigurationBuilder()
.add(new MemoryConfigurationSource([
{ path:"host:url",value:"http://127.0.0.1" },
{ path:"host:port",value:"3000" }
]))
.build();
const hostConfig = provider.getScoped("host");
const host = hostConfig.get("url").value;
const port = hostConfig.get("port").value;
In order to get a value of configuration, use getAsString
:
const provider = await new ConfigurationBuilder()
.add(new MemoryConfigurationSource([
{ path:"host:url",value:"http://127.0.0.1" },
{ path:"host:port",value:"3000" }
]))
.build();
const url = provider.getAsString("host:url","http://localhost");
// url = http://127.0.0.1
Sarina-Configuration allows developer to implement custom sources. To create your own source, you need to impement IConfigurationSource
and implement load
method
class MySource implements IConfigurationSource {
public async load(): Promise<ConfigurationElement[]> {
return [
{
path: 'host',
value: 'http://127.0.0.1',
},
];
}
}
const provider = await new ConfigurationBuilder()
.add(new MySource())
.build();
Sarina provides some built-in sources:
MemoryConfigurationSource
provides in memory configuration as array
or object
.EnvironmentConfigurationSource
provides elememtns by using process.env
. Just fork the project, make your changes send us a PR.