var assign = require('object-assign'); var pluralize = require('pluralize'); var isarray = require('lodash.isarray'); var Q = require('q'); var OKQuery = require('okquery'); var OKResource = require('okresource'); // Routes for views over collections have a special pattern // containing a free variable e.g. :id var UNBOUND_ROUTE_PATTERN = /:([a-zA-Z\-_]+)/; /** * OKView! * Is supplied DB queries and a template and is responsible * for resolving the queries, throwing the data into the templates, * and sending the response. */ function OKView(options) { if (!(this instanceof OKView)) return new OKView(options); options = options || {}; if (!options.template) throw new Error('No template provided to OKView.'); if (!options.meta) throw new Error('No meta resource provided to OKView'); if (!options.route) throw new Error('No route provided to OKView'); var route = options.route; var mount = options.mount || 'get'; this._template = options.template; var meta = this._meta = options.meta; var queries = this._queries = options.queries || []; // Whether this is a view for a specific resource or its // resource will be resolved later // TODO This bound / unbound thing can probably be expressed in a // less convoluted way. var unbound = this.unbound = !!UNBOUND_ROUTE_PATTERN.exec(route); Object.defineProperty(this, 'mount', { value: mount, writable: false, enumerable: true }); Object.defineProperty(this, 'route', { value: route, writable: false, enumerable: true }); this._middleware = createMiddleware(this); this._fetchTemplateData = unbound ? fetchUnbound : fetchBound; function fetchUnbound(id) { // TODO Janky return fetchTemplateData(meta, [queries[0].get(id)]); } function fetchBound() { return fetchTemplateData(meta, queries); } } OKView.prototype.middleware = function() { return this._middleware; }; OKView.prototype.render = function(req, res, data) { this._template.render(data).then(function(html) { res.send(html); }).fail(errorHandler(req, res, data)); }; OKView.prototype.fetchTemplateData = function() { return this._fetchTemplateData.apply(this, arguments); }; /** * Unbound views need different middleware to resolve requests */ function createMiddleware(view) { if (view.unbound) { return unboundMiddleware(view); } else { return boundMiddleware(view); } } // Note that these middleware do not call next // and should thus always be added at the end of the // middleware chain. /** * Creates middleware for a view which does not * yet have a resource id associated with it */ function unboundMiddleware(view) { var paramName = getParamName(view.route); return function(req, res, next) { var id = req.params[paramName]; view.fetchTemplateData(id).then(function(data) { view.render(req, res, data); }).fail(errorHandler(req, res, next)); }; } /** * Creates middleware for a view which already * has a resource id associated with it */ function boundMiddleware(view) { return function(req, res, next) { view.fetchTemplateData().then(function(data) { view.render(req, res, data); }).fail(errorHandler(req, res, next)); }; } /** * TODO BS error handling for now */ function errorHandler(req, res, next) { return function(err) { res.send(err.stack); } } /** * Given a route with a free variable, return the * name of the variable, e.g. :id returns id */ function getParamName(route) { route = route || ''; var matches = UNBOUND_ROUTE_PATTERN.exec(route) || []; return matches[1]; } /** * Takes a meta data query and an array of resource queries * and returns a promise for an object merging all queried * data, pluralizing keys where necessary. * * Lil bit convoluted, sorry. */ function fetchTemplateData(meta, queries) { return Q.promise(function(resolve, reject) { return Q.all( [meta.get()].concat(queries.map(function(query) { return query.get(); }))) .then(function(results) { var metadata = results.shift(); var normalized = results.reduce(function(cache, result, i) { // Huh? Bail if (!result) return cache; var resource = queries[i].resource; var type = queries[i].type; var manyResult = isarray(result); // Inform template of ID in generic field if (manyResult) { result = result.map(function(data) { return assign({}, data, {id: data[resource.idField]}) }); } else { result = assign({}, result, {id: result[resource.idField]}); } // If we have a lot of results for a certain type, // we pluralize the key and yield an array of results if (cache[type] || manyResult) { var plural = pluralize(type); delete cache[type]; cache[plural] = []; if (manyResult) { cache[plural] = cache[plural].concat(result); } else { cache[plural].push(result); } } else { cache[type] = result; } return cache; }, {meta: metadata}); resolve(normalized); }).fail(reject); }); } module.exports = OKView;