Skip to content

Instantly share code, notes, and snippets.

@nguyentien98
Created November 12, 2018 03:16
Show Gist options
  • Save nguyentien98/cda6d2d8f8259530536662b9deebf301 to your computer and use it in GitHub Desktop.
Save nguyentien98/cda6d2d8f8259530536662b9deebf301 to your computer and use it in GitHub Desktop.
Config Getter

File config.ts có nội dung như sau

import * as fs from 'fs';

class Config {

    public get(config: string, defaultVal?: string): any {
        let configSplited = config.split('.');
        let [fileName] = configSplited;
        let configFile = this.importFile(fileName);
        let configValue: any;

        for (let elm of configSplited) {
            configValue = configValue === undefined ? configFile[elm] : configValue[elm];
        }

        if (configValue === undefined) {
            return !defaultVal ? null : defaultVal;
        }

        return configValue;
    }

    public importFile(fileName) {
        if (!fs.existsSync(__dirname + '/' + fileName + '.ts') && !fs.existsSync(__dirname + '/' + fileName + '.js')) {
            return [];
        }

        return require(`./${fileName}`);
    }

}

export default new Config();

Tạo các file config ngang hàng với file trên. Ví dụ app.ts

export const app = {
  validation: {
    shift: {
      morning: 100,
      afternoon: 100,
    },
  },
  
  notification: {
    category: {
      number_of_posts: 15,
    },
    title: "My project"
  },

};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment