Skip to content

Commit

Permalink
fit(fill model properties from ReferencesMany relationship)
Browse files Browse the repository at this point in the history
  • Loading branch information
alltouch committed Aug 6, 2017
1 parent 42ede51 commit cfd5c49
Showing 1 changed file with 37 additions and 12 deletions.
49 changes: 37 additions & 12 deletions lib/deserializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -66,17 +66,42 @@ 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)
return
}
})
}

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;
})
}
}

0 comments on commit cfd5c49

Please sign in to comment.