1
votes

I have a UserSession model defined as such:

App.UserSession = DS.Model.extend({
  authToken: attr('string'),
  firstName: attr('string'),
  lastName: attr('string')
});

When a user is logging in, I'm making an AJAX POST request to my back-end which return a JSON representation such as:

{
  "user_session": {
    "id": 1,
    "auth_token": "token_here",
    "first_name": "John",
    "last_name": "Doe"
  }
}

Now normally, if I were to do the following, Ember Data would take care of automatically serializing the JSON and adding the object:

App.UserSession.find(<session-id>);

When I'm making a manual AJAX call though, is there an easy way to load the JSON returned into an Ember Data store object without having to manually deserialize it?

Edited for clarity:

The below does not work, but I'm hoping to find some function that does what's described above, which may look similar to the call below.

App.UserSession.load(<session-json>);
2
I think it wouldn't work because your JSON doesn't have an id property.MilkyWayJoe
Forgot to include "id", but it's definitely present. .load() doesn't work, I'm just trying to find something that does.Alex Coleman

2 Answers

5
votes

If you're using the latest version (11) of ember-data there is a breaking change for loading data.

Loading Data

Previously, some features of the store, such as load(), assumed a single adapter.

If you want to load data from your backend without the application asking for it (for example, through a WebSockets stream), use this API:

store.adapterForType(App.Person).load(store, App.Person, payload);

This API will also handle sideloaded and embedded data. We plan to add a more convenient version of this API in the future.

https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md#loading-data

You're going to want to grab the instance of your store. If you're in a controller you can do:

@get('store')

You can also do:

App.__container__.lookup('store:main')

which isn't recommended as it's using the internal API (noted by the __ surrounding the container call) which isn't guaranteed to not change.

Once you have your instance of the store you can load in your UserSession:

@get('store').adapterForType(App.UserSession).load(@get('store'), App.UserSession, sessionJson['user_session']);
0
votes

The previous answer is outdated, but the concept is still the same.

I believe the correct way to handle this is with this.get('store').pushPayload({data: ...})