Skip to content

Commit

Permalink
Merge pull request #12 from jelhan/ref-true
Browse files Browse the repository at this point in the history
Use `ref: true`
  • Loading branch information
jelhan authored Jul 22, 2016
2 parents a163f56 + 7884e99 commit 2ce5923
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 15 deletions.
22 changes: 8 additions & 14 deletions lib/responses/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,30 +69,24 @@ module.exports = function json() {
relationships.forEach(function (relationship) {
var alias = relationship.alias;
var collection = relationship.model || relationship.collection;

Model = sails.models[collection];
// Related model attributes
opts[alias] = {
attributes: modelUtils.getOwnAttributes(Model)
};
// add models as relationships
modelUtils.getRef(Model, function (ref) {
opts[alias].ref = ref;
});
if (modelUtils.isPopulatedRelationship(data, relationship)) {
modelUtils.getRef(Model, function (ref) {
opts[alias].ref = ref;
});
} else {
opts[alias].ref = true;
}
// Compound Document options
opts[alias].included = sails.config.jsonapi.compoundDoc;
});

// normalize relationships
// jsonapi-serializer expects every relationship to be wrapped in an object
relationships.forEach(function (relationship) {
var alias = relationship.alias;
var value = data[alias];
// assume string or number to be id of related ressource
if (typeof value === 'string' || typeof value === 'number') {
data[alias] = { id: value };
}
});

// Clean up data (removes 'add' and 'remove' functions)
data = normUtils.normalizeData(data);

Expand Down
22 changes: 22 additions & 0 deletions lib/utils/model-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,25 @@ exports.getRelationships = function (req) {

return associations;
};

// return true if relationship is populated
exports.isPopulatedRelationship = function (data, relationship) {
var _ = require('lodash');
// data may be an array of records or a single record
var datum = _.isArray(data) ? data[0] : data;
var value = datum[relationship.alias];
// value may be a single value (to-one) or an array (to-many)
var singleValue = _.isArray(value) ? value[0] : value;

// assume that relationship is not populated if
if (
// it's a number
_.isNumber(singleValue) ||
// it's a string
_.isString(singleValue)
) {
return false;
} else {
return true;
}
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"url": "https://github.com/IanVS/sails-hook-jsonapi"
},
"dependencies": {
"jsonapi-serializer": "^3.1.0",
"jsonapi-serializer": "^3.2.0",
"lodash": "^4.5.0",
"pluralize": "^1.1.2",
"sails-build-dictionary": "^0.10.1"
Expand Down

0 comments on commit 2ce5923

Please sign in to comment.