file-conf
v2.0.1
Published
A structured configuration system with options for saving in multiple file formats.
Downloads
8
Readme
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 FileConf
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 zod
npm
package as its peer dependency. You must be able to write a zod schema to use this module.
Example
import { FileConf } from 'file-conf';
import z from 'zod';
const mySchema = z
.object({
mode: z.enum(['development', 'production']).default('development'),
database: z
.object({
host: z.string().default('somewhere.net'),
port: z.coerce.number().default(5432),
user: z.string().default('REDACTED'),
password: z.string().default('REDACTED')
})
.default({})
})
.strict()
.default({});
/**
* @typedef {object} ConfigSchema
* @property {string} mode
* @property {object} database
* @property {string} database.host
* @property {number} database.port
* @property {string} database.user
* @property {string} database.password
*/
class Config extends FileConf {
constructor() {
super(mySchema, { format: 'yaml' });
/** @type {ConfigSchema} */
this.$json;
}
get mode() {
return this.$json.mode;
}
get database() {
return this.$json.database;
}
}
const c = new Config();
console.log(c.mode); //prints "development"
console.log(c.database.user); //prints "REDACTED"
const dbConf = { database: { user: 'admin' } };
//passing "true" saves valid changes to disk
console.log(c.update(dbConf, true);); //prints "true" because it was a valid update
console.log(c.update({notValid: 1}, true)) //prints false because it was an invalid update
console.log(c.database.user); //prints "admin"