a_Fraley
a_Fraley

Reputation: 342

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 protected]',
        is_staff: false
      }).save();
    }
  }
});

The REST API is expecting this request:

{
    "data": {
        "type": "User",
        "id": null,
        "attributes": {
            "username": "bill",
            "email": "[email protected]",
            "is_staff": false
        }
    }
}

Ember-data is sending this:

{
    data: 
    {
        attributes: 
        {
            username: "bill", 
            email: "[email protected]", 
            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 jQuery.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 protected]',
            is_staff: false
          });
      }
    });

Upvotes: 1

Views: 292

Answers (1)

DanielSpaniel
DanielSpaniel

Reputation: 171

You are trying the normalizeCreateRecordResponse method, but that is for when you are getting data from the server back from the create record POST call.

If you want to modify the data sent TO the server you need:

https://guides.emberjs.com/v2.0.0/models/customizing-serializers/#toc_customizing-serializers

to use the serialize method ( there are other serialize methods for more fine grained control .. but this one is pretty simple to try out for what you want )

This link explains it. If you can't figure that out from there, let me know.

Upvotes: 1

Related Questions