"use strict"; const Promise = require("bluebird"); function withProperty(dataSource, id, property) { return withData(dataSource, id, (value) => { return value[property]; }); } function withData(dataSource, id, callback) { return function (args, context) { let {data} = context; return Promise.try(() => { if (data[dataSource] != null) { return data[dataSource].load(id); } else { throw new Error(`Specified data source '${dataSource}' does not exist`); } }).then((value) => { if (value != null) { return callback(value, args, context); } else { throw new Error(`Got a null value from data source '${dataSource}' for ID '${id}'`); } }); }; } let ID = Symbol("ID"); let LocalProperties = Symbol("localProperties"); module.exports = { ID: ID, LocalProperties: LocalProperties, createDataObject: function createDataObject(mappings) { let object = {}; if (mappings[LocalProperties] != null) { Object.assign(object, mappings[LocalProperties]); } for (let [dataSource, items] of Object.entries(mappings)) { if (items[ID] != null) { let id = items[ID]; for (let [property, source] of Object.entries(items)) { if (typeof source === "string") { object[property] = withProperty(dataSource, id, source); } else if (typeof source === "function") { object[property] = withData(dataSource, id, source); } } } else { throw new Error(`No object ID was provided for the '${dataSource}' data source`); } } return object; } };