Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ts-convict

kferrone3.7kISC1.1.0TypeScript support: included

Model style decorators for your convict config.

typescript, decorators, convict, config, configuration

readme

TS Convict

NPM version Build Status Coverage Status

GitHub forks GitHub stars

Annotate a class to define and validate your configs using convict just like you do with an ORM. Brings true serialized class types to your config when loaded. If you like annotating models classes with Typescript, then this package will work well. If your using a IOC/DI system, TSConvict will fit in real nice. The idea is inspired by projects like Typeorm and Inversify.

Contributing | Changelog | Convict | |---|---|---|

Requirements

Features

  • all the power and then some from convict
  • define convict schemas with decorators
  • get your config as serialized classes
  • extremely simple and intuitive implementation
  • very pretty code for defining your apps config

Installation

  1. Install the package and dependencies.

npm install ts-convict convict reflect-metadata --save
npm install @types/convict --save-dev

Optionally install a parser of your choice if your config is not JSON. For example you can also use YAML.

npm install js-yaml --save

  1. Make sure reflect-metadata Is configured correctly for Typescript.

2.1 tsconfig.json

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

2.2 Import in main file
index.ts

import "reflect-metadata";

or import with node command
node -r reflect-metadata

Project Setup

First we need a proper project setup like the one below with a folder to hold our config schema classes. This is a very simple Typescript folder structure.

MyProject
├── src                  // place of your TypeScript code
│   ├── config           // place where your config entities will go
│   │   ├── MyConfig.ts  // the main config
│   │   ├── Database.ts  // sample database config
│   │   └── SubConfig.ts // a nested config
│   ├── types.d.ts       // place to put your interfaces  
│   └── index.ts         // start point of your application
├── .gitignore           // standard gitignore file
├── config.yml           // Your apps config file
├── db.json              // Your apps other db config as json
├── package.json         // node module dependencies
├── README.md            // a readme file
└── tsconfig.json        // TypeScript compiler options

Take note of the src/config directory, here we will put our convict schema classes.
The classes will be annotated with convict schema definitions. This directory can be called whatever you like.

Useage

1. Define an Interface

It's a good idea to define an interface so your experience can be agile and include all the fancy IDE features. Interfaces also open an opportunity to have more than one implementation of your config, i.e. maybe youswitch to a convict competitor or maybe just have no validation on config at all, i.e. require('config.json').

src/types.d.ts

declare namespace config {
    export interface MyConfig {
        name: string;
        subConfig: SubConfig;
        db: Database;
    }
    export interface SubConfig {
        bar: number;
    }
    export interface Database {
        host: string;
        port: number;
        database: string;
        user: string;
        password: string;
    }
}

2. Define a Schema Class

Now we can define a schema class and decorate it. The parameter for @Property decorator is simply a convict SchemaObj like in normal convict. You can read all about the possible options in convicts documentation.

src/config/MyConfig.ts

import { Property, Config } from 'ts-convict';
import SubConfig from './SubConfig';
import Database from './Database';
import * as yaml from 'js-yaml';
import { url, ipaddress } from "convict-format-with-validator";

@Config({

    // optional default file to load, no errors if it doesn't exist
    file: 'config.yml',// relative to NODE_PATH or cwd()

    // optional parameter. Defaults to 'strict', can also be 'warn'
    validationMethod: 'strict',

    // optionally add parsers like yaml or toml
    parser: { 
        extension: ['yml', 'yaml'], 
        parse: yaml.safeLoad
    },

    //optional extra formats to use in validation
    formats: {
        url,
        ipaddress,
    }

})
export class MyConfig implements config.MyConfig {

    // ts-convict will use the Typescript type if no format given
    @Property({
        doc: 'The name of the thing',
        default: 'Convict',
        env: 'MY_CONFIG_NAME'
    })
    public name: string;

    @Property(SubConfig)
    public subConfig: config.SubConfig;

    @Property(Database)
    public db: config.Database;

}

src/config/SubConfig.ts

import { Property } from 'ts-convict';

export class SubConfig implements config.SubConfig {
    @Property({
        doc: 'A sub prop',
        default: 3,
        env: 'SUB_CONFIG_BAR',
        format: 'int'
    })
    public bar: number;

    public message: string = "I am an unmanaged config property";
}

Database.ts

import { Property } from 'ts-convict';

export class Database implements config.Database {
    @Property({
        doc: "The database host",
        default: "localhost",
        format: "url",
        env: "DATABASE_HOST"
    })
    public host: string;

    @Property({
        doc: "The database port",
        default: 5432,
        format: "port",
        env: "DATABASE_PORT"
    })
    public port: number;

    @Property({
        doc: "The database db",
        default: "my_db",
        env: "DATABASE_DB"
    })
    public database: string;

    @Property({
        doc: "The database user",
        default: "magik",
        env: "DATABASE_USER"
    })
    public user: string;

    @Property({
        doc: "The database pass",
        default: "secretpassword",
        sensitive: true,
        env: "DATABASE_PASS"
    })
    public password: string;
}

3. Make a Configuration

Now we can make our configuration for our app. This can be a hardcoded Object in your code, a json file, a yaml file, or however you do it. In the end it's up to you how you type out and load the data.

config.yml

name: Cool App
subConfig: 
    bar: 5
db:
    user: devuser
    password: devpassword

db.json

{
    "user": "someuser",
    "password": "somepassword",
    "host": "somedb.com"
}

4. Load it up

We have a couple of ways to load it up so you can choose what works for your unique situation. The example below is the simplest way in the spirit of TL;DR.

src/index.ts

import { TSConvict } from 'ts-convict';
import { MyConfig } from "./config/MyConfig";
import { Database } from "./config/Database";
import { SubConfig } from "./config/SubConfig";

// example loading default file defined in @Config
const myConfigLoader = new TSConvict<MyConfig>(MyConfig);
const myConfig: MyConfig = myConfigLoader.load();

// example loading with file passed to load
const dbLoader = new TSConvict<Database>(Database);
const dbConfig: Database = dbLoader.load('db.json');

// example loading an ad hoc config class with raw data
const rawSub: config.SubConfig = {
    bar: 22
};
const subLoader = new TSConvict<SubConfig>(SubConfig);
const subConfig = subLoader.load(rawSub);

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

[1.1.0] - 2021-02-12

Added

  • allow empty configs
  • exposecd convicts validationMethod in the Config annotation
  • exposed formats object in @Config, now one can add as many custom formats as they like
  • updated all of the dependencies and fixed the issues which came with the updates
  • code is linted with eslint now instead of the deprecated tslint

[1.0.0] - 2020-01-22

Added

  • completely refactored to use reflect-metadata as global schema repo
  • now implementation only needs a single class to pass into TSConvict to load it's entire schema
  • removed all of the metaSchemaRepo functionality so there is no adding to global anymore
  • ability to load many file paths at once to cascade configs
  • @Config decorator now just accepts a parser and a basefile to try and load if no file is passed to laod.
  • converted all the tests to use the new TSConvict class

[0.2.0] - 2019-11-02

Added

  • renamed to just convict-model, dropped the @akirix
  • a lot of useful tests and even debug scripts
  • types are guessed when format left empty on a property annotation
  • simple top level gettter for convictModel called getConvictModel
  • refactored a bunch to open up more features from convict
  • defined the Config annotation
  • two ways to create now, both have the same useage too
    • simpleCreate: recursive create flat configs and merge to one
    • create: get the whole convict schema and whole config and load all at once

[0.1.0] - 2019-10-10

Added

  • A super well done changelog. Hope you agree.
  • Other convict model classes as a property
  • some good tests

[0.0.5] - 2019-05-16

Added

  • load convict model classes using classes or paths to files to load
  • write simple model classes. Simple as in basic data types for the attributes
  • ci scripts for dev-ops automation using Travis with Github
  • unit testing scripts