UNPKG

regard

Version:

Sugar-interface to access multiple data sources.

117 lines (91 loc) 2.67 kB
var _ = require('lodash'), Connector = require('../connector'), Jsonfile = require('jsonfile'); exports = module.exports = FsConnector; var Methods = exports.Methods = { READ: 'read', WRITE: 'write' }; var KEY = exports.KEY = Connector.generateKey(__filename); var SETTINGS = exports.SETTINGS = { method: Methods.READ, options: {} }; function FsConnector() { if (!(this instanceof FsConnector)) { return new FsConnector(); } Connector.call(this, KEY, SETTINGS); this.handler(Connector.DEFAULT_HANDLER, handleRequest, beforeRequest); this.handler(Methods.READ, handleRequest, beforeReadRequest); this.handler(Methods.WRITE, handleRequest, beforeWriteRequest); } FsConnector.prototype = _.create(Connector.prototype); FsConnector.prototype.checkPath = canAcceptPath; FsConnector.prototype.checkMethod = canAcceptMethod; function canAcceptPath(path) { return _.isString(path) && _.includes(['/', '.'], _(path).at(0).pop()); } function canAcceptMethod(method) { return _.isString(method) && _.has(Methods, method.toUpperCase()); } function beforeRequest(request, method, path, obj, options) { if (_.isString(method) && !canAcceptMethod(method)) { options = obj; obj = path; path = method; method = undefined; } if (_.isObject(method)) { options = path; obj = method; method = undefined; } if (_.isObject(path)) { options = obj; obj = path; path = undefined; } if (_.isString(path) && !_.isEmpty(path)) { request.path = [request.path, path].join('/'); } if (!_.isUndefined(method)) { method = request.context.method = method.toLowerCase(); } if (_.isObject(obj)) { if (method === Methods.WRITE) { request.context.obj = obj; } else { options = obj; } } if (_.isObject(options)) { request.context.options = options; } return request; } function beforeReadRequest(request, path, options) { return beforeRequest(request, Methods.READ, path, options); } function beforeWriteRequest(request, path, obj, options) { return beforeRequest(request, Methods.WRITE, path, obj, options); } function handleRequest(request, resolve, reject) { var path = request.path, context = request.context, method = context.method, obj = context.obj, options = context.options, write = method === Methods.WRITE, func = _.partial(Jsonfile.readFile, path, options); if (write) { func = _.partial(Jsonfile.writeFile, path, obj, options); } func(function callback(error, response) { if (error) { reject(error); } else { resolve(write ? obj : response); } }); }