Marco Faustinelli
Marco Faustinelli

Reputation: 4206

Ember.js - Mapping legacy JSON response to data model

My legacy server JSON response looks like this:

{ "foo": { … }, "bars": ["a", "b", "c", …] }

How can I map this into an Ember Data Model by extending a RESTAdapter?

My best attempt so far is the following:

app/models/rule-lookup.js:

import DS from 'ember-data';
export default DS.Model.extend({
  foo: DS.attr(),
  bars: DS.attr(),
});


app/models/foo.js:

import DS from 'ember-data';
export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
});

When the user makes a choice in a select, in the controller I fetch the model with:

this.store.findRecord('rule-lookup', id);

In the adapter (inside application.js) I have put the following statements:

import DS from 'ember-data';
export default DS.RESTAdapter.extend({
  urlForFindRecord(id, modelName, snapshot) {
    switch (modelName) {
      case 'rule-lookup': {
        return `api/keys/${id}/rules/0/200`;
      }
    }
  },
});

The import using findRecord fails silently, with just a warning:

WARNING: Encountered "bars" in payload, but no model was found for model name "bar" (resolved model name using panel@serializer:rest:.modelNameFromPayloadKey("bars"))`
TypeError: Cannot read property '_internalModel' of undefined

I am using:

Ember      : 1.13.7
Ember Data : 1.13.8

Upvotes: 1

Views: 186

Answers (1)

razielgn
razielgn

Reputation: 46

I've been bitten by this problem in the past. The "correct" way to go seemed to be to override methods such as extract and normalize in your model's serializer. That is achieved by creating a new file such as:

in app/serializers/rule-lookup.js

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
  // override here
});

But in the end I couldn't make it work.

So I've solved it at the "root" by changing the "flat" response emitted by the server from:

{ "id": 1, "label": "something" }

to:

{ "rule-lookup": { "id": 1, "label": "something" } }

Upvotes: 1

Related Questions