var path = require('path'); var isarray = require('lodash.isarray'); var pluralize = require('pluralize'); var Q = require('q'); /** * OKUtils! * Cross cutting concerns n stuff */ module.exports = { /** * 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. */ fetchTemplateData: function fetchTemplateData(meta, queries, options) { return Q.promise(function(resolve, reject) { return Q.all( [meta.get()].concat(queries.map(function(query) { return query.get(options); }))) .then(function(results) { var metadata = results.shift(); var normalized = results.reduce(function(data, result, i) { var type = queries[i].type; if (isarray(result)) { data[pluralize(type)] = result; } else { data[type] = result; } return data; }, {meta: metadata}); resolve(normalized); }, reject); }); }, /** * Return a copy of the route with a trailing slash */ withTrailingSlash: function withTrailingSlash(route) { route = route || ''; return path.normalize(route + '/'); }, /** * Return a copy of the route without a trailing slash */ withoutTrailingSlash: function withoutTrailingSlash(route) { route = route || ''; return route.charAt(route.length - 1) === '/' ? route.slice(0, -1) : route; } };