Skip to content

Commit 492afa3

Browse files
Pierre WatineSeyZ
authored andcommitted
Add metaData function
1 parent afbfa62 commit 492afa3

2 files changed

Lines changed: 32 additions & 7 deletions

File tree

lib/serializer-utils.js

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,13 +97,17 @@ module.exports = function (collectionName, record, payload, opts) {
9797
}
9898

9999
function getMeta(current, meta) {
100-
return _mapValues(meta, function (value) {
101-
if (isFunction(value)) {
102-
return value(record, current);
103-
} else {
104-
return value;
105-
}
106-
});
100+
if (isFunction(meta)) {
101+
return meta(record);
102+
} else {
103+
return _mapValues(meta, function (value) {
104+
if (isFunction(value)) {
105+
return value(record, current);
106+
} else {
107+
return value;
108+
}
109+
});
110+
}
107111
}
108112

109113
function pick(obj, attributes) {

test/serializer.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,27 @@ describe('Options', function () {
328328
expect(json.data[1].meta.count).equal(1);
329329
done(null, json);
330330
});
331+
332+
it('should set the meta according to the func return', function (done) {
333+
var dataSet = [{
334+
id: '54735750e16638ba1eee59cb',
335+
firstName: 'Sandro',
336+
lastName: 'Munda'
337+
}, {
338+
id: '5490143e69e49d0c8f9fc6bc',
339+
firstName: 'Lawrence',
340+
lastName: 'Bennett'
341+
}];
342+
343+
var json = new JSONAPISerializer('user', {
344+
attributes: ['firstName', 'lastName'],
345+
dataMeta: function (record) { return { copyright: record.firstName + ' ' + record.lastName }; }
346+
}).serialize(dataSet);
347+
348+
expect(json.data[0].meta.copyright).equal("Sandro Munda");
349+
expect(json.data[1].meta.copyright).equal("Lawrence Bennett");
350+
done(null, json);
351+
});
331352
});
332353

333354
describe('included', function () {

0 commit comments

Comments
 (0)