From 2b61f055d499bd47144dc04aebcce74a7797f643 Mon Sep 17 00:00:00 2001 From: Sandro Munda Date: Mon, 6 Jul 2015 17:20:44 +0200 Subject: [PATCH] Add the typeForAttribute option. Closes #11. --- README.md | 2 ++ lib/serializer-utils.js | 11 +++++++++-- test/serializer.js | 20 ++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 483ee6a..c3ef834 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ API](http://jsonapi.org) (1.0 compliant). - *dataLinks*: An object that describes the links inside data. Values can be *string* or a *function* (see examples below) - *relationshipLinks*: An object that describes the links inside relationships. Values can be *string* or a *function* (see examples below) - *keyForAttribute*: A function that maps the attribute (passed as an argument) to the key. Attributes are dasherized by default. + - *pluralizeType*: A boolean to indicate if the type must be pluralized or not. Default: true. + - *typeForAttribute*: A function that maps the attribute (passed as an argument) to the type you want to override. Option *pluralizeType* ignored if set. ## Examples diff --git a/lib/serializer-utils.js b/lib/serializer-utils.js index 788c9da..1fb7105 100644 --- a/lib/serializer-utils.js +++ b/lib/serializer-utils.js @@ -29,8 +29,15 @@ module.exports = function (collectionName, record, payload, opts) { } function getType(str) { - return !_.isUndefined(opts.pluralizeType) && !opts.pluralizeType ? str : - inflection.pluralize(str); + var type = str; + + if (_.isFunction(opts.typeForAttribute)) { + type = opts.typeForAttribute(str); + } else if (_.isUndefined(opts.pluralizeType) || opts.pluralizeType) { + type = inflection.pluralize(type); + } + + return type; } function getLinks(current, links) { diff --git a/test/serializer.js b/test/serializer.js index 9b6ca1e..293af5c 100644 --- a/test/serializer.js +++ b/test/serializer.js @@ -56,6 +56,26 @@ describe('Options', function () { }); }); + describe('typeForAttribute', function () { + it('should set the type according to the func return', function (done) { + var dataSet = { + id: '1', + firstName: 'Sandro', + lastName: 'Munda', + }; + + new JsonApiSerializer('user', dataSet, { + attributes: ['firstName', 'lastName'], + typeForAttribute: function (attribute) { + return attribute + '_foo'; + } + }).then(function (json) { + expect(json.data.type).equal('user_foo'); + done(null, json); + }); + }); + }); + describe('included', function () { it('should include or not the compount documents', function (done) { var dataSet = [{