lundi 6 juillet 2015

Custom adapter createRecord method leaves null id record in store

I'm currently attempting to write a custom ember-data adapter to use with my backend and I have encountered a problem I just can't seem to find a solution to.

I'm using ember-cli 0.2.7 ember-data 1.0.0-beta.17

My adapter extends the existing RESTAdapter and as intended by the authors of ember-data I'm 1. serializing the snapshot 2. sending it to my server 3. receiving the reply from the server, now including the id that was set server-side 4. using the normalized payload to resolve the promise

as such:

createRecord: function(store, type, snapshot) {
    var ws = this.get('ws');
    var data = this.serialize(snapshot, {includeId: false});
    return new Ember.RSVP.Promise(function(resolve, reject) {
        var route = type.typeKey;
        ws.create(route, data,
            function(context, data) {
                try {
                    var resdata = store.normalize(route, data);
                    resolve(resdata);
                } catch(err) {
                    console.error(err);
                }
            },
            function(context, data) {
                console.log(data);
                reject(data);
            }
        );
    });
}

Where the normalized payload being resolved looks like:

{
    name: "Some name",
    id: 115,
    reference: "Some reference"
}

The problem is that resolving doesn't update the current record in store, but instead creates a completely new record. The result being I end up with 2 identical records: one with a correct numerical ID corresponding to the backend and another with an ID set to null.

I've tried calling

store.updateId(snapshot.record, {id: resdata.id});

from the adapter and this updates the record with the correct ID but throws an error and leaves the record in a dirty state. Also, I don't think the updateId method is intended to be called from the adapter but I'm not sure and perhaps some else know more about that?

What is the correct way of updating the id of the record in the store? Any advice that can help me solve this issue is highly appreciated.




Aucun commentaire:

Enregistrer un commentaire