samedi 12 novembre 2016

Ember: Custom JSONAPISerializer

I am having trouble persisting data back to the API after I create a new record in the datastore.

// routes/application.js

import Ember from 'ember';

export default Ember.Route.extend({
  model(){
    return this.store.findAll('user');
  },
  actions: {
    test(name){
      this.store.createRecord('user', {
        username: name,
        email: 'email@email.com',
        is_staff: false
      }).save();
    }

  }
});

The REST API is expecting this request:

{
    "data": {
        "type": "User",
        "id": null,
        "attributes": {
            "username": "bill",
            "email": "email@email.com",
            "is_staff": false
        }
    }
}

Ember-data is sending this:

{
    data: 
    {
        attributes: 
        {
            username: "bill", 
            email: "email@email.com", 
            is-staff: false
        }, 
    type: "users"
    }
}

Here is what I have for a custom serializer, but Ember is not seeing it. Am I doing this right?

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({

  normalizeCreateRecordResponse(store, type, payload){
    return {
      data: {
        type: 'User',
        id: null,
        attributes: {
          username: payload.username,
          email: payload.email,
          is_staff: payload.is_staff
        }
      }
    }
  }

});

On a side note, to make sure that the API is working right, I can send the data via a jQuey.post():

// routes/application.js

    import Ember from 'ember';

    export default Ember.Route.extend({
      model(){
        return this.store.findAll('user');
      },
      actions: {
        test(name){
          Ember.$.post('http://localhost:8000/api/users/', {
            username: name,
            email: 'email@email.com',
            is_staff: false
          });
      }
    });




Aucun commentaire:

Enregistrer un commentaire