node-microsvc-lib
Version:
NodeJS microservice framework library
306 lines • 13.2 kB
JavaScript
/**
* Created by pedrosousabarreto@gmail.com on 15/Jan/2019.
*/
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppBaseConfigs = exports.ServiceConfigs = void 0;
const uuid = __importStar(require("uuid"));
const service_params_1 = require("./service_params");
const path = __importStar(require("path"));
const CLASS_NAME = "ServiceConfigs";
class ServiceConfigs {
constructor(base_config_path, base_configs, configs_provider) {
this._conf_files_dir_path = base_config_path;
this._configs_provider = configs_provider;
this._service_params_values = new Map();
this._service_feature_flags_values = new Map();
this._service_secret_values = new Map();
this._env = base_configs.env;
this._solution_name = base_configs.solution_name;
this._app_name = base_configs.app_name;
this._app_version = base_configs.app_version;
this._app_api_prefix = base_configs.app_api_prefix;
this._app_api_version = base_configs.app_api_version;
//computed props
this._dev_mode = this._env.toUpperCase().startsWith("DEV");
// common computed
this._app_full_name = this._solution_name + "__" + this._env + "__" + this._app_name;
this._app_full_name_version = this._app_full_name + "__" + this._app_version;
if (this._app_api_prefix)
this._app_base_url = this._app_api_prefix + "/api" + (this._app_api_version ? `/v${this._app_api_version}` : "");
else
this._app_base_url = "/";
// instance specific
this._instance_id = uuid.v4();
this._instance_name = this._app_full_name_version + "__" + this._instance_id;
this._log_start_values();
// load the param.js file
this._load_default_params_file();
// always load the default params, feature flags and secrets to the correspondent "_values"
this._load_default_params();
this._load_default_feature_flags();
this._load_default_secrets();
// check if a per APP_ENV file exists and execute its overrides
this._override_from_env_file();
}
// getters
get env() {
return this._env;
}
get solution_name() {
return this._solution_name;
}
get app_name() {
return this._app_name;
}
get app_version() {
return this._app_version;
}
get app_api_prefix() {
return this._app_api_prefix;
}
get app_api_version() {
return this._app_api_version;
}
// computed
get dev_mode() {
return this._dev_mode;
}
get app_full_name() {
return this._app_full_name;
}
get app_full_name_version() {
return this._app_full_name_version;
}
get app_base_url() {
return this._app_base_url;
}
get instance_id() {
return this._instance_id;
}
get instance_name() {
return this._instance_name;
}
// get everything it needs and prepare the object to be used
init() {
return __awaiter(this, void 0, void 0, function* () {
// create an internal structure with values of params and feature_flags
// so get_param_value and get_feature_flag_value can work
if (this._configs_provider == null) {
this._override_from_envvars();
return Promise.resolve();
}
// const keys: string[] = Array.from(this._service_params_values.keys()).concat(
// Array.from(this._service_feature_flags_values.keys()),
// Array.from(this._service_secret_values.keys())
// );
const keys = this._service_params.all_keys();
// go to consul or whatever configuration service
yield this._configs_provider.init(keys).catch((err) => {
console.error(err);
return Promise.reject(err);
}).then(() => {
this._override_from_serviceprovider();
this._override_from_envvars();
Promise.resolve();
});
});
}
get_param_value(name) {
return this._service_params_values.get(name) !== undefined ? this._service_params_values.get(name) : null;
}
get_feature_flag_value(name) {
return this._service_feature_flags_values.get(name);
}
get_secret_value(name) {
return this._service_secret_values.get(name) !== undefined ? this._service_secret_values.get(name) : null;
}
override_param_value(name, new_value) {
if (!this._service_params.has(name))
throw new Error(`Non-existing param - name: ${name} - cannot be overwritten`);
this._service_params_values.set(name, new_value);
console.debug(`${CLASS_NAME} - param '${name}' overridden`);
}
;
override_feature_flag_value(name, new_value) {
if (!this._service_params.has(name))
throw new Error(`Non-existing feature flag - name: ${name} - cannot be overwritten`);
this._service_feature_flags_values.set(name, new_value);
console.debug(`${CLASS_NAME} - feature flag '${name}' overridden`);
}
;
override_secret_value(name, new_value) {
if (!this._service_params.has(name))
throw new Error(`Non-existing secret - name: ${name} - cannot be overwritten`);
this._service_secret_values.set(name, new_value);
console.debug(`${CLASS_NAME} - secret '${name}' overridden`);
}
;
_load_default_params_file() {
// const caller_file = GetCallerFile();
// const caller_path = path.dirname(caller_file);
const filename = path.resolve(this._conf_files_dir_path, "params");
let params_obj;
try {
params_obj = require(filename);
}
catch (e) {
throw new Error(`params.js file not found - one is required in path ${this._conf_files_dir_path}`);
}
if (typeof (params_obj) != "object")
throw new Error("invalid params obj from params.js file");
if (!(params_obj instanceof service_params_1.ServiceParams))
throw new Error("invalid params obj from params.js file, not instance of ServiceParams");
this._service_params = params_obj;
}
_load_default_params() {
// what we can init already
this._service_params.get_all_params().forEach((param) => {
this._service_params_values.set(param.name, param.default_value);
});
}
_load_default_feature_flags() {
this._service_params.get_all_feature_flags().forEach((feature_flag) => {
this._service_feature_flags_values.set(feature_flag.name, feature_flag.default_value);
});
}
_load_default_secrets() {
this._service_params.get_all_secrets().forEach((secret) => {
this._service_secret_values.set(secret.name, secret.default_value);
});
}
_override_from_env_file() {
const filename = path.resolve(this._conf_files_dir_path, "overrides." + this._env);
try {
require(filename)(this);
console.info(`${CLASS_NAME} - env var overrides file loaded successfully from path: ${filename}`);
}
catch (e) {
if (e.code === "MODULE_NOT_FOUND")
console.warn(`${CLASS_NAME} - env var overrides file NOT FOUND in path: ${filename}`);
else {
console.error(e, `${CLASS_NAME} - error in env var overrides file in path: ${filename}`);
}
}
}
_override_from_envvars() {
this._service_params.get_all_params().forEach((param) => {
if (process.env.hasOwnProperty(param.name.toUpperCase()) && process.env[param.name.toUpperCase()])
this._service_params_values.set(param.name, this._convert_from_string(process.env[param.name.toUpperCase()] || "", param.type));
});
this._service_params.get_all_feature_flags().forEach((feature_flag) => {
if (process.env.hasOwnProperty(feature_flag.name.toUpperCase()))
this._service_feature_flags_values.set(feature_flag.name, this._convert_from_string(process.env[feature_flag.name.toUpperCase()] || "", service_params_1.ParamTypes.BOOL));
// this._service_feature_flags_values.set(feature_flag.name, (process.env[feature_flag.name] === "true" || process.env[feature_flag.name] === "1"));
});
this._service_params.get_all_secrets().forEach((secret) => {
if (process.env.hasOwnProperty(secret.name.toUpperCase()) && process.env[secret.name.toUpperCase()])
this._service_secret_values.set(secret.name, process.env[secret.name.toUpperCase()]);
});
}
_override_from_serviceprovider() {
this._service_params.get_all_params().forEach((param) => {
// @ts-ignore
const val_str = this._configs_provider.get_value(param.name);
if (val_str)
this._service_params_values.set(param.name, this._convert_from_string(val_str, param.type));
});
this._service_params.get_all_feature_flags().forEach((feature_flag) => {
// @ts-ignore
const val_str = this._configs_provider.get_value(feature_flag.name);
if (val_str)
this._service_feature_flags_values.set(feature_flag.name, this._convert_from_string(val_str, service_params_1.ParamTypes.BOOL));
});
this._service_params.get_all_secrets().forEach((secret) => {
// @ts-ignore
const val_str = this._configs_provider.get_value(secret.name);
if (val_str)
this._service_secret_values.set(secret.name, this._convert_from_string(val_str, service_params_1.ParamTypes.STRING));
});
}
_convert_from_string(value, destination_type) {
switch (destination_type) {
case service_params_1.ParamTypes.STRING:
return value;
break;
case service_params_1.ParamTypes.INT_NUMBER:
try {
const num = Number.parseInt(value);
return num;
}
catch (e) {
return null;
}
return value;
break;
case service_params_1.ParamTypes.FLOAT_NUMBER:
try {
const num = Number.parseFloat(value);
return num;
}
catch (e) {
return null;
}
return value;
break;
case service_params_1.ParamTypes.BOOL:
try {
const bool_value = value.toLowerCase() == "true" || value == "1" ? true : false;
return bool_value;
}
catch (e) {
return null;
}
return value;
break;
default:
return value;
break;
}
}
_log_start_values() {
console.info(`${CLASS_NAME} - Loaded with:
\tenv: ${this._env}
\tdev_mode: ${this._dev_mode}
\tenv: ${this._env}
\tsolution name: ${this._solution_name}
\tapp name: ${this._app_name}
\tapp version: ${this._app_version}
\tinstance id: ${this._instance_id}
\tinstance name: ${this._instance_name}
\tconfigs path: ${this._conf_files_dir_path}`);
}
}
exports.ServiceConfigs = ServiceConfigs;
class AppBaseConfigs {
}
exports.AppBaseConfigs = AppBaseConfigs;
//# sourceMappingURL=service_configs.js.map