Search code examples
javascriptember.jsember-dataember-cliember-cli-mirage

Simple Ember Data Issue with Mirage (Error: Encountered a resource object with an undefined type )


I have some experience with Ember.js, and am now going through creating a new project, with Mirage to stub the data for now.

I'm going through the Ember.js Tutorial step by step but keep getting this error when querying for records:

Encountered a resource object with an undefined type (resolved resource using DS.JSONAPISerializer)

I do realize that a similar question has been asked, but it did not include the Mirage addon, and I also went through all of the techniques answered in that question.


mirage/config.js

export default function() {
  this.namespace = '/api'

  this.get('/todos', function() {
    return {
      data: [
        {
          text: 'Bring in garbage cans',
          completed: false,
          timesViewed: 3
        },
        {
          text: 'Look at the plants',
          completed: false,
          timesViewed: 0
        }
      ]
    }
  })
}

app/models/todo.js

import DS from 'ember-data';

export default DS.Model.extend({
    text: DS.attr(),
    completed: DS.attr(),
    timesViewed: DS.attr()
});

app/routes/index.js

import Route from '@ember/routing/route';

export default Route.extend({
    model() {
        return this.store.findAll('todo')
    }
});

app/adapters/application.js

import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    namespace: 'api'
});

I've been formatting the response from Mirage in all kinds of ways, even doing the double quotes on keys, but that shouldn't be necessary since I believe mirage serializes it.

Any help on what I'm missing here is appreciated.


Solution

  • I think the problem you are facing is due to the fact that your mirage data isn't formatted as-per JSON-API specifications.

    mirage/config.js =>

    export default function() {
    this.namespace = '/api'
    
    this.get('/todos', function() {
      return {
        data: [
          {
              type: "todos",
              id: 1,
              attributes: {
              text: "Bring in garbage cans",
              completed: false,
              timesViewed: 3
              }
          },
          {
              type: "todos",
              id: 2,
              attributes: {
              text: "Look at the plants",
              completed: false,
              timesViewed: 0
              }
          }
          ]
      }
    });
    

    }

    Try out this code and see if the issue is resolved.

    If you are looking for a way to dynamically generate mirage data according to JSON-API spec., see this sample code -> sample code for dynamic mirage data! Cheers 🙌