Search code examples
ruby-on-railsrestember.jsjson-api

Ember understanding serializers and adapters


I am troubling with communication between my frontend application (ember 2.3.1, ember-data 2.3.3) and backend (rails 5 with jsonapi serializers).

I will try to describe all situation that I have.

On backend side I want to send responses in jsonapi and get requests in the REST format. I am using serializers and how I inspected backend send right responses. For example {"data":[{"id":"1","type":"projects","attributes":{"title":"one"},"links...

On ember side I defined jsonapi adapter and rest serializer. When ember receives data from backend I've got warning in console like Encountered "data" in payload, but no model was found for model name "datum" (resolved model name using smart-task-ember@serializer:application:.modelNameFromPayloadKey("data"). When I changed serializer in ember from rest to jsonapi everything going to work as well. But requests going to the backend in jsonapi format. I've received next params {"data"=>{"attributes"=>{"title"=>"test"}, "type"=>"projects"}, "controller"=>"projects", "action"=>"create", "project"=>{}} instead {"project"=>{"title"=>"qwe"}, "controller"=>"projects", "action"=>"create"}

I can't understand why rest serializer and jsonapi adapter affect each other and how can I use REST serializer in ember. I spent a lot of time on this strange behavior but can't understand anything.

I will be happy to receive any kind of help :)


Solution

  • Adapters determine how EmberData will work with backend. It includes, in general, URL format and request headers.

    Serializers determine how data will be processed and formatted. So, in your case, you just need to change data format when data will be send to backend. To implement this, you should override serialize method.

    For example:

    import DS from 'ember-data';
    
    export default DS.JSONSerializer.extend({
      serialize(snapshot, options) {
        var json = this._super(...arguments);
        var res = json.data;
        return data;
      }
    });
    

    It will delete root node data from request. So you can transform json to your desired structure before send.