File Conf
A structured configuration system with options for saving in multiple file formats.
Usage
To use this package, you need to create your own configuration class that extends the ConfigFile
class provided by this module. This allows you to expose values that you want available as well
as validate input that you allow through during runtime. This package includes the joi
npm
package as one of it's dependencies. You must be able to write a joi schema to use this module.
Example
import { ConfigFile } from 'file-conf';
import Joi from 'joi';
interface Skill {
name: string;
yearsExperience: number;
}
interface MySettings {
name: string;
age: number;
skills: Skill[];
}
const schema = Joi.object<MySettings>({
name: Joi.string().default('Joel'),
age: Joi.number().min(0).max(120).default(25),
skills: Joi.array()
.items(
Joi.object<Skill>({
name: Joi.string().required(),
yearsExperience: Joi.number().min(1).required()
})
)
.default([])
});
class MyConf extends ConfigFile<MySettings> {
constructor() {
super(schema, 'test.yaml');
}
public get Name() {
return this.data.name;
}
public get Age() {
return this.data.age;
}
public set Age(value) {
this.data.age = value;
this.validate();
}
public get Skills() {
return this.data.skills;
}
public hasSkill(name: string) {
return this.data.skills.filter((s) => s.name == name).length > 0;
}
public addSkill(skill: Skill) {
this.data.skills.push(skill);
this.validate();
}
}
const myConf = new MyConf(); //create an instance - recommend singleton pattern use through application
if (myConf.isNewFile()) myConf.save(); //save a new copy of the default if no file was found
console.log(myConf.Age); //prints 25
myConf.Age = 35; //set the age to 35
console.log(myConf.Age); //prints 35
myConf.reload(); //reload the existing configuration file (if there is one - default otherwise)
console.log(myConf.Age); //prints 25
myConf.Age = 35; //set the age to 35
console.log(myConf.Age); //prints 35
myConf.save(); //save the current state of the configuration to the file
myConf.reload(); //reload the configuration from the file
console.log(myConf.Age); //prints 35 (because the change was recorded to the file)