How to create a custom Serializer for Ember data

后端 未结 1 445
粉色の甜心
粉色の甜心 2020-12-29 11:43

I have an API that returns JSON that is not properly formatted for Ember\'s consumption. Instead of this (what ember is expecting):

{ events: [
    { id: 1,          


        
相关标签:
1条回答
  • 2020-12-29 12:17

    I am assuming that the responses contain the IDs only, and that you are trying to extract them.

    You will want to subclass DS.JSONSerializer, which supplies the basic behavior for dealing with JSON payloads. In particular, you will want to override the extractHasMany hook:

    // elsewhere in your file
    function singularize(key) {
      // remove the trailing `s`. You might want to store a hash of
      // plural->singular if you deal with names that don't follow
      // this pattern
      return key.substr(0, key.length - 1);
    }
    
    DS.JSONSerializer.extend({
      extractHasMany: function(type, hash, key) {
        return hash[key][singularize(key)].id;
      }
    })
    
    0 讨论(0)
提交回复
热议问题