mardi 30 août 2016

EmberJS 2.7 How to restructure/reformat/customize data returned from the store

I have what I think is a very simple issue, but I just don't get how to do this data manipulation. This sadly didn't help, even though it's the same pain I am feeling with Ember.

Here is a route:

route/dashboard.js:

import Ember from 'ember';

export default Ember.Route.extend({
    // this is for testing, normally we get the data from the store
    model: function() {
        return this.get('modelTestData');
    },

    modelTestData: [{
        name: 'gear',
        colorByPoint: true,
        data: [
            {y: 10, name: 'Test1'},
            {y: 12, name: 'Test2'},
            {y: 40, name: 'Test3'}
            ]
    }],

});

The structure of the 'modelTestData' object has to be exactly like that as it is passed into a child component that needs it structured that way.

I can easily get my data from the API and put it into the model:

model: function() {
    return this.store.get('category');
},

But then I need to restructure it...but how?

I have to somehow iterate over the categories collection and extract parts of data from each record to replace the 'data' part of the modelTestData object.

So I have 3 issues I am completely stumped on:

  1. How to 'get at' the attributes I need from the model?
  2. How to structure them as an array of objects with 'y' and 'name'?
  3. How to assign that structure to 'data' instead of it being hardcoded?

Categories is a JSONAPI object like this:

{
   "data":[
      {
         "id":"1",
         "type":"categories",
         "attributes":{
            "name":"Carrying system",
            "total-weight":{
               "grams":"100.0",
               "ounces":"0.0"
            }
         }
      },
      {
         "id":"2",
         "type":"categories",
         "attributes":{
            "name":"Shelter system",
            "total-weight":{
               "grams":"10.0",
               "ounces":"0.0"
            }
         }
      }
   ]
}

I need to iterate this structure and grab the category.attribute.name and the attribute.total-weight.grams [ignore ounces, it's not used].

I need to map the grams value to 'y' and the name to 'name' in modelTestData.

Note that the category data is used in other routes for other purposes exactly as returned by the API. So I don't want to change the model structure itself, or what the API returns...that will break other parts of the app that do use 'category' in its original structure.

This is a specific use case that this route needs to massage the data to pass to the child component as per the structure of modelTestData.

I also wonder whether this data manipulation task belongs in a route?

Should I somehow do this in the serliazer adapter, creating a new structure as say 'categoryWeights' so I can then do:

model: function() {
    return this.store.get('categoryWeights');
},




Aucun commentaire:

Enregistrer un commentaire