regard
Version:
Sugar-interface to access multiple data sources.
114 lines (86 loc) • 2.69 kB
JavaScript
var _ = require('lodash'),
Connector = require('../connector'),
Monk = require('monk');
exports = module.exports = MongodbConnector;
var Methods = exports.Methods = [
'index', 'indexes', 'dropIndex', 'dropIndexes',
'insert',
'id',
'find', 'findById', 'findOne', 'findAndModify',
'remove'
];
var KEY = exports.KEY = Connector.generateKey(__filename);
var SETTINGS = exports.SETTINGS = {
method: 'find'
};
var dbs = {};
function MongodbConnector() {
if (!(this instanceof MongodbConnector)) {
return new MongodbConnector();
}
Connector.call(this, KEY, SETTINGS);
bindHandlers(this);
}
MongodbConnector.prototype = _.create(Connector.prototype);
MongodbConnector.prototype.checkPath = canAcceptPath;
MongodbConnector.prototype.checkMethod = canAcceptMethod;
MongodbConnector.prototype.onCreateEndpoint = createClient;
function bindHandlers($this) {
$this.handler(Connector.DEFAULT_HANDLER, handleRequest, beforeRequest);
_.forEach(Methods, function bindHandler(method) {
$this.handler(method, handleRequest, function beforeHandler(request) {
return _.partial(beforeRequest, request, method).apply($this, _.slice(arguments, 1));
});
});
}
function canAcceptPath(path) {
return _.startsWith(path, 'mongodb://');
}
function canAcceptMethod(method) {
return _.isString(method) && _.includes(Methods, method);
}
function createClient(endpoint) {
var uri = endpoint.path,
opts = endpoint.context;
if (endpoint.root) {
dbs[endpoint.name] = Monk(uri, opts, _.constant());
} else {
endpoint.context.collection = collectionNameFromUri(uri);
dbs[endpoint.name] = dbs[endpoint.parent.name];
}
}
function beforeRequest(request) {
var args = _.cloneDeep(_.slice(arguments, 1)),
method = args.shift(),
collection;
if (_.isString(method) && !canAcceptMethod(method)) {
collection = method;
method = undefined;
} else {
if (_.isString(args[0])) {
collection = args.shift();
}
}
if (!_.isUndefined(method)) {
request.context.method = method;
request.handler = method;
}
if (_.isString(collection) && !_.isEmpty(collection)) {
request.context.collection = collection;
}
request.args = args;
return request;
}
function collectionNameFromUri(uri) {
return _(uri).split('/').pop();
}
function handleRequest(request, resolve, reject) {
var db = dbs[request.endpoint.name],
collection = request.context.collection,
method = request.handler,
args = request.args,
processing;
collection = db.get(collection);
processing = _.get(collection, method).apply(collection, args);
processing.then(resolve, reject);
}