UNPKG

1.72 kBJavaScriptView Raw
1'use strict';
2var isFunction = require('lodash/isFunction');
3var _mapValues = require('lodash/mapValues');
4var SerializerUtils = require('./serializer-utils');
5
6module.exports = function (collectionName, records, opts) {
7 this.serialize = function (records) {
8 var that = this;
9 var payload = {};
10
11 function getLinks(links) {
12 return _mapValues(links, function (value) {
13 if (isFunction(value)) {
14 return value(records);
15 } else {
16 return value;
17 }
18 });
19 }
20
21 function collection() {
22 payload.data = [];
23
24 records.forEach(function (record) {
25 var serializerUtils = new SerializerUtils(that.collectionName, record,
26 payload, that.opts);
27 payload.data.push(serializerUtils.perform());
28 });
29
30 return payload;
31 }
32
33 function resource() {
34 payload.data = new SerializerUtils(that.collectionName, records, payload,
35 that.opts).perform(records);
36
37 return payload;
38 }
39
40 if (that.opts.topLevelLinks) {
41 payload.links = getLinks(that.opts.topLevelLinks);
42 }
43
44 if (that.opts.meta) {
45 payload.meta = _mapValues(that.opts.meta, function (value) {
46 if (isFunction(value)) {
47 return value(records);
48 } else {
49 return value;
50 }
51 });
52 }
53
54 if (Array.isArray(records)) {
55 return collection(records);
56 } else {
57 return resource(records);
58 }
59 };
60
61 if (arguments.length === 3) {
62 // legacy behavior
63 this.collectionName = collectionName;
64 this.opts = opts;
65 return this.serialize(records);
66 } else {
67 // treat as a reusable serializer
68 this.collectionName = collectionName;
69 this.opts = records;
70 }
71};