file-conf
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

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)

Readme

Keywords

none

Package Sidebar

Install

npm i file-conf

Weekly Downloads

0

Version

1.2.0

License

MIT

Unpacked Size

16.2 kB

Total Files

28

Last publish

Collaborators

  • driverjb