summaryrefslogtreecommitdiff
path: root/app/node_modules/okutil/index.js
blob: 01041b68110ee6137b82393934cb37f367ba3402 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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(cache, result, i) {
          var resource = queries[i].resource;
          var type = queries[i].type;
          var plural = pluralize(type);
          if (isarray(result)) {
            result = result.map(function(data) {
              // Inform template of ID in generic way
              data.id = data[resource.idField];
              return data;
            });
          } else {
            // Inform template of ID in generic way
            result.id = result[resource.idField];
            result = [result]
          }
          cache[plural] = cache[plural] || [];
          cache[plural] = cache[plural].concat(result);
          return cache;
        }, {meta: metadata});
        resolve(normalized);
      }).fail(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;
  }

};