Payload with metadata on JSONSerializer


#1

Hello,

I’m trying to create a paginated results on my app using the JSONSerializer, but I can’t figure out how the server should return the payload to get some extra information (metadata) i.e the current page, items per page, total items, etc.

I have access to change the response on the server, but, I don’t want to complain with the JSON-API conventions (many changes on the server).

I tried with this JSON payload (a bit formated)

{
"data":[
  {"_id":"563a20f38088b108c447bea8","title":"First post","description":"Description","active":0},
  {"_id":"5643478b631b6f12178b4567","title":"second","description":"second","updated_at":"2015-11-11 13:50:03","created_at":"2015-11-11 13:50:03"}
],
"meta":{
  "total":3,"per_page":15,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from":1,"to":3
  }
}

I’m getting this error on _normalizeResponse method

payload.map is not a function TypeError: payload.map is not a function

The questions are. Is posible to get extra information (metadata) with the JSONSerializer? or should I use the JSONAPISerializer for that. Should I implement the normalizeResponse method or there is a easy way to change the response to get working out-of-the-box.

Thanks in advance,


#2

I figured out implementing the normalizeArrayResponse method

export default DS.JSONSerializer.extend({
  primaryKey: '_id',
  isNewSerializerAPI: true,

  normalizeArrayResponse: function (store, primaryModelClass, payload, id, requestType) {
    var _this = this;

    var documentHash = {
      data: null,
      included: []
    };

    var meta = this.extractMeta(store, primaryModelClass, payload);
    if (meta) {
      Ember.assert("The `meta` returned from `extractMeta` has to be an object, not \"" + Ember.typeOf(meta) + "\".", Ember.typeOf(meta) === "object");
      documentHash.meta = meta;
    }

    documentHash.data = payload.data.map(function (item) {
      var _normalize2 = _this.normalize(primaryModelClass, item);
      var data = _normalize2.data;
      return data;
    });

    return documentHash;
  },
});

I copied this function from _normalizeResponse method with some modifications, the important line is

documentHash.data = payload.data.map(function (item) {

instead of

documentHash.data = payload.map(function (item) {