lundi 6 juillet 2015

Record duplication with DS.EmbeddedRecordsMixin in DS.ActiveModelSerializer

This is a classic situation where received JSON needed to be altered before ember-data can use it, and here how it looks after those transformation:

{  
  "profile":{  
    "first_name":"fsdf",
    "last_name":"sdfsdf",
    "company":null,
    "birthday":null,
    "emails":[  
      {  
        "address":"sdfsdfsdf",
        "id":1,
        "kind":"main",
        "contactable_type":"Profile",
        "contactable_id":1
      }
    ],
    "addresses":[  

    ],
    "id":1
  }
}

that is done in the model's serializer extract hook:

export default DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    emails: { embedded: 'always' },
    addresses: { embedded: 'always' }
  },
  extract: function(store, typeClass, payload, id, requestType) {
    let profile = normalizeProfile(payload, id),
      profileJSON = requestType == 'findAll' ? { profiles: [profile] } : {     profile: profile };
    return this._super(store, typeClass, profileJSON, id, requestType);
  },
});

and this._super(store, typeClass, profileJSON, id, requestType); returns

{
  "company":null,
  "birthday":null,
  "emails":[
    1
  ],
  "addresses":[

  ],
  "id":1,
  "firstName":"fsdf",
  "lastName":"sdfsdf"
}

when it's saved for the first time everything is ok, but when profile saved again email is duplicated - there are two of them in the store one with id and one without id. Address and kind properties are equal. Ember-data 1.13.4




Aucun commentaire:

Enregistrer un commentaire