lemon-core
Version:
Lemon Serverless Micro-Service Platform
131 lines • 5.35 kB
JavaScript
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());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRunParam = exports.loadDataYml = exports.hasCredentials = exports.credentials = exports.asyncCredentials = exports.loadJsonSync = void 0;
/**
* `lib/tools.ts`
* - additional helper.
*
* ex:
* ```ts
* const environ = require('lemon-core/dist/environ').default;
* const $env = environ(process)
* ```
*
* @author Steve Jung <steve@lemoncloud.io>
* @date 2019-08-09 initial typescript version.
* @date 2018-05-23 initial version
* @date 2019-11-26 cleanup and optimized for `lemon-core#v2`
*
* @copyright (C) 2019 LemonCloud Co Ltd. - All Rights Reserved.
*/
const fs_1 = __importDefault(require("fs"));
const js_yaml_1 = __importDefault(require("js-yaml"));
const aws_sdk_1 = __importDefault(require("aws-sdk"));
//! load json in sync.
const loadJsonSync = (name, def = {}) => {
name = !name.startsWith('./') ? `./${name}` : name;
try {
const rawdata = fs_1.default.readFileSync(name);
return JSON.parse(rawdata.toString());
}
catch (e) {
if (def && typeof def === 'object')
def.error = `${e.message || e}`;
return def;
}
};
exports.loadJsonSync = loadJsonSync;
//! dynamic loading credentials by profile. (search PROFILE -> NAME)
const asyncCredentials = (profile) => __awaiter(void 0, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
let credentials = null;
const callback = (e, r) => {
// e || console.error('! credentials.res :=', r);
// e && console.error('! credentials.err :=', e);
if (e)
reject(e);
else
resolve(r || credentials);
};
try {
//WARN! - could not catch AWS.Error `Profile null not found` via callback.
credentials = new aws_sdk_1.default.SharedIniFileCredentials({ profile, callback });
aws_sdk_1.default.config.credentials = credentials;
}
catch (e) {
callback(e);
}
});
});
exports.asyncCredentials = asyncCredentials;
//! dynamic loading credentials by profile. (search PROFILE -> NAME)
const credentials = (profile) => {
if (!profile)
return '';
// console.info('! credentials.profile =', profile);
// WARN! - could not catch AWS.Error `Profile null not found` via callback.
const credentials = new aws_sdk_1.default.SharedIniFileCredentials({ profile });
aws_sdk_1.default.config.credentials = credentials;
return `${profile}`;
};
exports.credentials = credentials;
//! return whether AWS credentials set
const hasCredentials = () => {
return !!aws_sdk_1.default.config.credentials;
};
exports.hasCredentials = hasCredentials;
//! load yml data via './data/<file>.yml'
const loadDataYml = (file, folder) => {
folder = folder || 'data';
const path = `./${folder}/` + file + (file.endsWith('.yml') ? '' : '.yml');
if (!fs_1.default.existsSync(path))
throw new Error('404 NOT FOUND - data-file:' + path);
return js_yaml_1.default.load(fs_1.default.readFileSync(path, 'utf8'));
};
exports.loadDataYml = loadDataYml;
// get running parameter like -h api.
const getRunParam = (o, defval, argv) => {
// export function getRunParam<U extends boolean | number | string | object>(o: string, defval: U, argv?: string[]): U {
// eslint-disable-next-line no-param-reassign
argv = argv || process.argv || []; // use scope.
const nm = `-${o}`;
let i = argv.indexOf(nm);
i = i > 0 ? i : argv.indexOf(o);
i = i >= 0 ? i : argv.indexOf(`-${nm}`); // lookup -o => --o.
if (i >= 0) {
const val = argv[i + 1];
if (typeof defval === 'boolean') {
// transform to boolean.
return val === 'true' || val === 't' || val === 'y' || val === '1';
}
else if (typeof defval === 'number') {
// convert to integer.
return Math.round(Number(val) / 1);
}
else if (typeof defval === 'object') {
// array or object
if ((val.startsWith('[') && val.endsWith(']')) || (val.startsWith('{') && val.endsWith('}')))
return JSON.parse(val);
else if (Array.isArray(defval))
return `${val}`.split(', ');
else
return { value: val };
}
return val;
}
return defval;
};
exports.getRunParam = getRunParam;
//# sourceMappingURL=shared.js.map
;