@andrew1 wrote:
Hi everyone,
I'm working with a kind of funky api so I need to normalize the data from it into the JSON API that Ember Data wants. I have 2 models in Ember Data:
Task = DS.Model.extend( { constraints: DS.hasMany('constraint') ... Constraint = DS.Model.extend( { task: DS.belongsTo('task') constraintType: DS.attr('string') field: DS.attr('string') operator: DS.attr('string') value: DS.attr('number') ....
My API inlines
constraints
inside thetask
response as an array. My goal is to normalizeconstraints
out oftasks
on the front end to make application development easier for us.I tried to follow the instructions spelled out in the Ember Data 1.13 release and use the
normalizeResponse
hook on theTaskSerializer
. However, all of the embedded records are stripped out of thearguments
passed intonormalizeResponse
.My next thought was to use the
normalize
hook. This is better because thehash
passed intonormalize
has the raw data from the api in it:It seems like I should be able to mutate the task data and put all of the
constraints
into theincluded
array, return that fromnormalize
and let Ember Data handle the rest. Here's an example of what I'm returning fromnormalize
:The problem is, this won't create the
constraints
in Ember Data. Thetask
is created OK but there are no associatedconstraints
.My current work-around is to
push
theconstraints
onto thestore
myself in thenormalize
hook:normalize: (typeClass, hash) -> normalizedTask = @_super(arguments...) included = hash.attributes.constraints.map((constraint, index) => normalizedConstraint = @store.normalize('constraint', constraint) @store.push(normalizedConstraint) <--- why do I need to do this ? return normalizedConstraint.data ) constraintRelationships = included.map((constraint) => return {type: constraint.type, id: constraint.id} ) normalizedTask.data.relationships['constraints'] = {data: constraintRelationships} normalizedTask['included'] = included return normalizedTask
This seems OK to me but I thought it was no longer necessary to push embedded models into the store manually in the
normalize
hook. Any feedback on this approach or tips on how to do it better would be greatly appreciated.Thanks!
Posts: 1
Participants: 1