Object property value resolver
Utility to recursively iterate over an object and use the provided handler
to asynchronously resolve/convert property values.
Can be used to allow runtime-resolution of properties for values that cannot be determined when the object is created, via functions, 'macro' strings or any other strategy provided by the handler.
A contrived example may look something like:
const data = {
first: '#0',
anArray: ['five','eight','#3'],
nested: {
value: '#2'
},
dynamic: function(items) {
// Can return promises here if needed!
return `The best is ${items[2]}`;
}
};
function handler(value) {
let choices = ['one','two','three','four'];
if (typeof value === 'function') {
return value(choices);
}
if (typeof value === 'string') {
// Strings starting with a '#' character are treated as 'macros'
// and will be replaced by the value in the choices array
// at the specified index.
if (value.startsWith('#')) {
const index = value.replace('#','');
return choices[index];
}
}
return value;
}
resolve(data, handler).then(result => {
console.log(result);
// Output:
// {
// first: 'one',
// anArray: [ 'five', 'eight', 'four' ],
// nested: { value: 'three' },
// dynamic: 'The best is three'
// }
});
Install
Installation using Yarn is recommended.
yarn add @frctl/resolve
Requirements
@frctl/resolve
requires Node >= v6.0