diff --git a/lib/deserializer.js b/lib/deserializer.js index 092b885..9134a9e 100644 --- a/lib/deserializer.js +++ b/lib/deserializer.js @@ -45,14 +45,14 @@ module.exports = function deserializer (options, cb) { afterDeserialize(deserializeOptions, function (err, deserializeOptions) { if (err) return cb(err) - belongsToRelationships(deserializeOptions) + fillFromRelationships(deserializeOptions) return cb(null, deserializeOptions) }) }) }) } -function belongsToRelationships (options) { +function fillFromRelationships (options) { var data = options.data var model = options.model @@ -66,17 +66,41 @@ function belongsToRelationships (options) { var type = serverRelation.type // only handle belongsTo - if (type !== 'belongsTo') return - - var fkName = serverRelation.keyFrom - var modelTo = serverRelation.modelFrom - - if (!modelTo) return false + if (type === 'belongsTo') { + belongsToRelation(serverRelation, relationship.data, options) + return + } - if (!relationship.data) { - options.result[fkName] = null - } else { - options.result[fkName] = relationship.data.id + if (type === 'referencesMany') { + referencesManyRelation(serverRelation, relationship.data, options) } }) } + +function belongsToRelation (serverRelation, data, options) { + var fkName = serverRelation.keyFrom + var modelTo = serverRelation.modelFrom + + if (!modelTo) return + + if (!data) { + options.result[fkName] = null + } else { + options.result[fkName] = data.id + } +} + +function referencesManyRelation (serverRelation, data, options) { + var fkName = serverRelation.keyFrom + var modelTo = serverRelation.modelFrom + + if (!modelTo) return + + if (!data) { + options.result[fkName] = [] + } else { + options.result[fkName] = data.map(function (resource) { + return resource.id + }) + } +}