options-defaults

Options-defaults design pattern implementation for reliable configuration. It merges objects deeply, overrides arrays and classes (different than Object) and the result remains strongly typed.

MIT 20 个版本
安装
npm install options-defaults
yarn add options-defaults
pnpm add options-defaults
bun add options-defaults
README

ts-options-defaults

Options-defaults design pattern implementation for reliable configuration. It merges objects deeply, overrides arrays and classes (different than Object) and the result remains strongly typed.

Table of contents

  1. Getting Started

  2. Usage

  3. Features

Getting Started

npm i ts-options-defaults

Usage

Design pattern

import { defaults } from 'ts-options-defaults';

export interface ISomeOptions {
    logger?: Partial<Console>;
}

export class Something {
    static defaults = {
        logger: console,
    };

    options: ISomeOptions & typeof Something.defaults;
    constructor(options?: ISomeOptions) {
        this.options = defaults(Rat.defaults, options);
    }
}

Behavior

import { defaults } from 'ts-options-defaults';

class TestLogger {
    constructor(public name = `TestLogger`) {}

    log() {
        console.log(`Call from ${this.name}`);
    }
}

const someDefaults = {
    console,
    nested: {
        property: 'default',
        shouldBeDefault: 'default',
        array: ['default1', 'default2'],
    },
};

const someOptions = {
    nested: {
        property: 'overriden',
        array: ['overriden1'],
    },
    array: ['overriden'],
};

const options = defaults(
    someDefaults,
    someOptions,
    {
        console: {
            log: () => {
                console.log(`TEST`);
            },
        },
    },
    {
        console: new TestLogger(),
    },
);

options.console.log(`log`); // "Call from TestLogger"
options.console.debug(`debug`); // "debug"

// options will be:
{
    "nested": {
        "property": "overriden",
        "shouldBeDefault": "default",
        "array": [
            "overriden1"
        ]
    },
    "array": [
        "overriden"
    ]
}

// someDefaults will not be mutated!

Features

Beats alternatives - better alternative to {...defaults, ...options} destructing and lodash _.defaults or _.merge Secure - immune to prototype pollution attack Simple - just 40 lines of clean TypeScript code Strongly typed - result remains strongly typed

版本列表
2.0.40 2022-06-17
2.0.39 2021-04-09
2.0.33 2021-04-09
2.0.32 2021-03-22
2.0.31 2021-03-17
2.0.30 2021-03-17
2.0.29 2021-03-16
2.0.28 2021-01-11
2.0.27 2021-01-11
2.0.25 2021-01-08
2.0.24 2020-12-21
2.0.22 2020-12-03
2.0.21 2020-11-25
2.0.18 2020-11-23
2.0.17 2020-11-17
2.0.16 2020-11-16
2.0.12-alpha.0 2020-10-23
2.0.10-alpha.0 2020-10-23
2.0.9 2020-10-23
0.0.0 2020-09-18