JSONAPISerializer attrs object


#1

Hi all,
I’m trying to represent my data from an API inside ember with ember-data.
The API I’m using - and contributing to code - it’s based on JSON API specs, with the exception of the camelCase key name.
The ouptut for a resource like license/:id is:

"data": { "type": "licenses", "id": "21", "attributes": {"contr_id":"21", "mice": "cat","contr_date_start":"2014-01-01","contr_date_end":"2014-12-31"},"relationships": { "owner":{
        "links": {
          "self": "/licenses/21/relationships/owner",
          "related": "/licenses/21/owner"
        },
        "data": { "type": "libraries", "id": "6"}
      }}}

This is my models/license.js:

import DS from 'ember-data';

export default DS.Model.extend({
  contrid: DS.attr('string'),
  contrdatestart: DS.attr('string'),
  contrdateend: DS.attr('string'),
  mice: DS.attr('string')
});

This is my serializers/license.js:

import DS from 'ember-data';

export default DS.JSONAPISerializer.extend({
    attrs: {
        contrdatestart: 'contr_date_start',
        contrdateend: 'contr_date_end',
        contrid: 'contr_id'
    }
});

The API is actually served with http-mock for test.
Using Ember Inspector visiting the URL licenses/21 this is the fields’ model instantiated:

contrid: undefined
contrdatestart: undefined
mice: cat

So it doesn’t work. Any hint on this and more generally on adapt my key names from API (which are with underscores) to be added to the ember-data model? If possible I will avoid convert them in camelCase format (underscores are not regularly used in the key names).

Thank you in advance!


#2

Original mistake: assume that the default behaviour of the serializer was to transform the keys name in camelCase. Default is dashed or spinal-case as expressed here in the keyForAttribute method section of the docs (so straightforward…).

By the way, attrs seems to not work so I tried keyForAttribute.
I need to thank @novascape for this that, actually, override the default transformation and returns the keys name from your attributes object in your JSON payload as they are.

In every case, bookmark the methods to manipulate strings in ember, here.