regard
Version:
Sugar-interface to access multiple data sources.
113 lines (87 loc) • 2.16 kB
JavaScript
var _ = require('lodash');
var exports = module.exports = Endpoint;
function Endpoint(key) {
if (!(this instanceof Endpoint)) {
return new Endpoint(key);
}
this.afterProcess = undefined;
this.beforeProcess = undefined;
this.context = {};
this.connector = undefined;
this.init = initEndpoint;
this.key = key;
this.keyDotted = key.split('/').join('.');
this.parent = undefined;
this.path = undefined;
this.root = false;
this.walk = _.partial(walkRoot, this);
}
function initEndpoint(path, context, before, after) {
var connector;
if (_.isPlainObject(path)) {
after = before;
before = context;
context = path;
path = undefined;
}
if (_.isFunction(path)) {
after = context;
before = path;
path = undefined;
}
if (_.isFunction(context)) {
after = before;
before = context;
context = undefined;
}
if (_.isString(context)) {
connector = context;
context = undefined;
}
if (!_.isPlainObject(context)) {
context = {};
}
if (_.isString(context.$path)) {
path = context.$path;
}
if (_.isFunction(context.$after)) {
after = context.$after;
}
if (_.isFunction(context.$before)) {
before = context.$before;
}
if (_.isString(context.$connector) || _.isObject(context.$connector)) {
connector = context.$connector;
}
while (_.isString(path) && path.length > 1 && _.endsWith(path, '/')) {
path = path.substring(0, path.length-1);
}
if (_.isFunction(before)) {
this.beforeProcess = before;
}
if (_.isFunction(after)) {
this.afterProcess = after;
}
if (!_.isUndefined(connector)) {
this.connector = connector;
}
if (_.isString(path) && !_.isEmpty(path)) {
this.path = path;
}
_.merge(this.context, context);
return this;
}
function walkRoot(endpoint, iteratee, property) {
if (_.isArray(iteratee)) {
var store = iteratee;
iteratee = function(value) {
if (_.isString(property)) {
value = _.get(value, property);
}
store.unshift(value);
}
}
for (; !_.isUndefined(endpoint); endpoint = endpoint.parent) {
iteratee(endpoint);
}
}