UNPKG

3.58 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const invalid_json_body_error_1 = require("../errors/invalid-json-body-error");
4const change_case_1 = require("change-case");
5const log_1 = require("../common/log");
6const Config_1 = require("../schemas/Config");
7const log = log_1.create('config');
8const schema = require('../schemas/Config.json');
9const { extractDefaultsFromSchema } = require('../lib/utils');
10const Ajv = require("ajv");
11const ajv = new Ajv();
12const ENV_PREFIX = 'CONNECTOR_';
13const BOOLEAN_VALUES = {
14 '1': true,
15 'true': true,
16 '0': false,
17 'false': false,
18 '': false
19};
20class Config extends Config_1.Config {
21 constructor() {
22 super();
23 this.loadDefaults();
24 this._validate = ajv.compile(schema);
25 this._validateAccount = ajv.compile(schema.properties.accounts.additionalProperties);
26 }
27 loadDefaults() {
28 Object.assign(this, extractDefaultsFromSchema(schema));
29 }
30 loadFromEnv(env) {
31 if (!env) {
32 env = process.env;
33 }
34 const unrecognizedEnvKeys = new Set(Object.keys(env).filter(key => key.startsWith(ENV_PREFIX)));
35 const config = {};
36 for (let key of Object.keys(schema.properties)) {
37 const envKey = ENV_PREFIX + change_case_1.constantCase(key);
38 const envValue = env[envKey];
39 unrecognizedEnvKeys.delete(envKey);
40 if (typeof envValue === 'string') {
41 switch (schema.properties[key].type) {
42 case 'string':
43 config[key] = envValue;
44 break;
45 case 'object':
46 case 'array':
47 try {
48 config[key] = JSON.parse(envValue);
49 }
50 catch (err) {
51 log.error('unable to parse config. key=%s', envKey);
52 }
53 break;
54 case 'boolean':
55 config[key] = BOOLEAN_VALUES[envValue] || false;
56 break;
57 case 'integer':
58 case 'number':
59 config[key] = Number(envValue);
60 break;
61 default:
62 throw new TypeError('Unknown JSON schema type: ' + schema.properties[key].type);
63 }
64 }
65 }
66 for (const key of unrecognizedEnvKeys) {
67 log.warn('unrecognized environment variable. key=%s', key);
68 }
69 this.validate(config);
70 Object.assign(this, config);
71 }
72 loadFromOpts(opts) {
73 this.validate(opts);
74 Object.assign(this, opts);
75 }
76 validate(config) {
77 if (!this._validate(config)) {
78 const firstError = this._validate.errors && this._validate.errors[0]
79 ? this._validate.errors[0]
80 : { message: 'unknown validation error', dataPath: '' };
81 throw new invalid_json_body_error_1.default('config failed to validate. error=' + firstError.message + ' dataPath=' + firstError.dataPath, this._validate.errors || []);
82 }
83 }
84 validateAccount(id, accountInfo) {
85 if (!this._validateAccount(accountInfo)) {
86 throw new invalid_json_body_error_1.default('account config failed to validate. id=' + id, this._validateAccount.errors || []);
87 }
88 }
89 get(key) {
90 return this[key];
91 }
92}
93exports.default = Config;
94//# sourceMappingURL=config.js.map
\No newline at end of file