UNPKG

dynamapping

Version:

replaces keys dynamically within the values for a raw, flat object

45 lines 1.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.replaceGlobalObjectValues = void 0; const fixValueIfChanged_1 = require("./fixValueIfChanged"); const { regExObjectValueString } = require('magicalstrings').constants.Regex.regExObjectValueString; const regExObjectValue = new RegExp(regExObjectValueString, 'g'); const globalObjects = { SETTINGS: 'nsInfo', ANSWERS: 'answers', SESSION: 'session', CONFIG: 'config', }; function convertIfObject(value) { if ((typeof value) === 'object') return JSON.stringify(value); return value; } /* replaces any global objects. Also set up to take answers so that you can use it with inquirer globally. The answers object is optional. */ function replaceGlobalObjectValues(value, session = {}, answers = {}) { if (Object.keys(session).length === 0 && Object.keys(answers).length === 0) { return value; } if (!value) return value; let newValue = ''; try { newValue = value.replace(regExObjectValue, function (match, objectName, key) { if (objectName === globalObjects.ANSWERS) return convertIfObject(answers[key]); if (objectName === globalObjects.SESSION) return convertIfObject(session[key]); throw new Error(`trying to replace an unrecognized object type: '${objectName}'`); }); } catch (error) { throw error; } return fixValueIfChanged_1.fixValueIfChanged(value, newValue); } exports.replaceGlobalObjectValues = replaceGlobalObjectValues; //# sourceMappingURL=replaceGlobalObjectValues.js.map