Accessing meta information passed in a json server response

后端 未结 3 926
一整个雨季
一整个雨季 2020-12-23 10:46

I am using the Ember-Data Rest-Adapter and the JSON returned from my server looks basically like the one in the Active Model Serializers Documentation

{
  \"         


        
3条回答
  •  独厮守ぢ
    2020-12-23 11:04

    I found a cleaner approach for extracting meta information from the server response with ember-data.

    We have to tell the serializer which meta-information to expect (in this case pagination):

     App.serializer = DS.RESTSerializer.create();
    
     App.serializer.configure({ pagination: 'pagination' });
    
     App.CustomAdapter = DS.RESTAdapter.extend({
       serializer: App.serializer
     });
    
     App.Store = DS.Store.extend({
       adapter: 'App.CustomAdapter'
     });
    

    After that every time the server sends a meta-property with a pagination object this object will be added to the store's TypeMaps property for the requested Model-Class.

    For example with the following response:

      {
        'meta': {'pagination': { 'page': 1, 'total': 10 } },
        'posts':[
          ...
        ]
      }
    

    The TypeMap for the App.Post-Model would include the pagination object after the posts have loaded.

    You can't observe the TypeMaps-property of the store directly so I added an computed property to the PostsController to have access to the requests pagination meta information:

     App.PostsController = Ember.ArrayController.extend({
        pagination: function () {
          if (this.get('model.isLoaded')) {
            modelType = this.get('model.type');
            this.get('store').typeMapFor(modelType).metadata.pagination
          }
        }.property('model.isLoaded')
     });
    

    I really don't think that's a great solution to the meta information problem but this is the best solution I was able to come up with yet with Ember-Data. Maybe this will be easier in the future.

提交回复
热议问题