ember.jsember-dataember-model

"str is undefined" on findRecord


I have a problem with model and serializer. I've looked at the documentation and can't find a solution. My app is connected to a django rest api.

Django response:

{
    "id": 1,
    "url": "http://localhost:8000/users/1/",
    "username": "username",
    "email": "xxx@email.com",
    "is_staff": true
}

The model:

export default DS.Model.extend({
    url : DS.attr('string'),
    username : DS.attr('string'),
    email : DS.attr('string'),
});

I've modified the response with a serializer to include "data":

export default DS.JSONAPISerializer.extend({
    primaryKey: 'id',
    normalizeFindRecordResponse(store, type, payload, id) {
        console.log('payload',payload)
        return {
            data: {
                'id': id,
                'url': payload.url,
                'username': payload.username,
                'email': payload.email,
            }
        } ; 
    }
});

The route:

export default Ember.Route.extend({
    model() {
        return this.store.findRecord('users', 1);
    }
});

Another version of the route same error:

export default Ember.Route.extend({
    model() {
        this.store.findRecord('users', '1').then(function(user){
            console.log('user', user);
        }).catch(function(e){
            console.log('e', e);
        });
    }    
});

Finally Ember inspector has the model but all values as undefined and "str is undefined" on console.

Image of ember inspector


Solution

  • 1.normalizeFindRecordResponse is not returning valid JSONAPI format, The below is the valid format,

    {
      "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
          // ... this article's attributes
        }        
      }
    }
    

    As you can see, you are missing type, attributes key.

    2.Your model file name should be user.js in singular.
    3.this.store.findRecord('users', 1) - here you need to use singluar form of the model so this.store.findRecord('user', 1)
    4.In your another attempt you are missing the return statement in model hook.