Skip to content

Commit

Permalink
Add the typeForAttribute option. Closes #11.
Browse files Browse the repository at this point in the history
  • Loading branch information
SeyZ committed Jul 6, 2015
1 parent 905b586 commit 2b61f05
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions lib/serializer-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
20 changes: 20 additions & 0 deletions test/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [{
Expand Down

0 comments on commit 2b61f05

Please sign in to comment.