Load multiple model data in same api call emberjs? - ember.js

So here is two models that i have defined in emberjs
match.js
import DS from 'ember-data';
export default DS.Model.extend({
team: DS.belongsTo('team', {async:true}),
opponent: DS.belongsTo('team', {async: true}),
type: DS.attr('string'),
squad: DS.attr('boolean')
});
and
team.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
logo: DS.attr('string')
});
I am already loading the match as a model. In the same api call i also want to load the model data for team. The api response that i have till now is
{
"meta":{
"type":"match"
},
"data":[
{
"id":1119536,
"type":"match",
"attributes":{
"id":1119536,
"team":{
"type":"team",
"id":1,
"attributes":{
"id":1,
"name":"England",
"logo":null
}
},
"opponent":{
"type":"team",
"id":3,
"attributes":{
"id":3,
"name":"Pakistan",
"logo":null
}
}
}
}
]
}
The match model data get loaded properly but i am having issues for the same with team data. The response is from network in browser and i already checked the model using ember plugin on browser that team data doesn't load. How can i use the same api call to load multiple models.

a few things to notice:
dont put the id in attributes
dont name an attribute type. Really dont! It's a reserved keyword.
relationships are not attributes and should be under relationships
use the included array to sideload data
ids must be strings
so for example this would be a valid payload:
{
"meta": {
"type": "match"
},
"data": [
{
"id": "1119536",
"type": "team",
"attributes": {
"match-type": "match"
},
"relationships": {
"team": {
"data": {
"type": "team",
"id": "1"
}
},
"opponent": {
"data": {
"type": "team",
"id": "3"
}
}
}
}
],
"included": [
{
"type": "team",
"id": "1",
"attributes": {
"name": "England",
"logo": null
}
},
{
"type": "team",
"id": "3",
"attributes": {
"name": "Pakistan",
"logo": null
}
}
]
}

Related

Ember Cli Mirage: Active Model Adapter with JSONAPISerializer

I am on halfway of implementing JSON API structure (with underscore attributes).
Actual state for development environment is:
I use the Active Model Adapter structure for requesting to the backend for resources and backend response me with JSON API structure.
In Application Serializer I am using JSONAPISerializer. I override methods:
serializeBelongsTo
keyForRelationship
keyForAttribute
serialize
serializeAttribute
serializeHasMany
and for development, everything works for me (backend in Rails communicate with Ember very good).
The problem is with Ember CLI Mirage and conventions (not sure if there are simple solutions or I need to override again methods in this addon).
Actual state with Ember Cli Mirage and test environment:
I am using import { JSONAPISerializer } from 'ember-cli-mirage';
and then trying to manipulate proper request and then transform it for JSON API format.
It could work like this:
Ember Adapter (Active Model Adapter format - with underscore attributes) ---> Mirage Serializer should get request (find resources created before in tests with associations) and then response it with JSON API format ---> JSON API Serializer could catch it and fill Ember DS.
For now, I have a missing part to serialize it for all cases to JSON API standard (with underscored attributes)
Where should I do this transformation to minimize overriding JSONAPISerializer Mirage Serializer.
I noticed that there are some helpers, but I have a problem to wrap this knowledge together
(http://www.ember-cli-mirage.com/docs/advanced/route-handlers#helpers)
UPDATE:
Example of structure from Backend:
{
"data": {
"id": "6",
"type": "first_resource",
"attributes": {
"id": 6,
"my_attribute": "my_attribute"
},
"relationships": {
"second_resources": {
"data": [
{
"id": "16",
"type": "second_resource"
}
]
},
"third_resource_other_type": {
"data": {
"id": "1",
"type": "third_resource"
}
},
"fourth_resource": {
"data": {
"id": "1",
"type": "fourth_resource"
}
}
},
"links": {
"fifth_resources": "/api/v1/first_resources/6/fifth_resources"
}
},
"included": [
{
"id": "1",
"type": "fourth_resource",
"attributes": {
"id": 1,
"my_attribute": "my_attribute"
},
"links": {
"sixth_resource": "/api/v1/fourth_resources/1/sixth_resource"
}
},
{
"id": "16",
"type": "second_resource",
"attributes": {
"id": 16,
"my_attribute": "my_attribute"
},
"relationships": {
"eighth_resources": {
"data": []
}
},
"links": {
"seventh_resources": "/api/v1/second_resources/16/seventh_resources"
}
},
{
"id": "17",
"type": "second_resource",
"attributes": {
"id": 17,
"my_attribute": "my_attribute"
},
"relationships": {
"eighth_resources": {
"data": []
}
},
"links": {
"seventh_resources": "/api/v1/second_resources/17/seventh_resources"
}
},
{
"id": "15",
"type": "second_resource",
"attributes": {
"id": 15,
"my_attribute": "my_attribute"
},
"relationships": {
"eighth_resources": {
"data": [
{
"id": "26",
"type": "eighth_resource"
},
{
"id": "24",
"type": "eighth_resource"
}
]
}
},
"links": {
"seventh_resources": "/api/v1/second_resources/15/seventh_resources"
}
},
{
"id": "26",
"type": "eighth_resource",
"attributes": {
"id": 26,
"my_attribute": "my_attribute"
}
}
]
}
UPDATE2
structure from mirage response:
data: {
attributes: {
my_attribute: 'my_attribute',
second_resource_ids: [36, 37],
fifth_resource_ids: []
},
id: 11,
relationships: {
third_resource_other_type: {data: null}
fourth_resource: {data: null}
second_resources: {data: []}
},
type: "first_resources"
}
resources in tests:
server.create('second-resource', {
id: 36,
first_resource_id: '11',
my_attribute: "my_attribute"
});
server.create('eighth-resource', {
id: 140,
second_resource_id: 37
});
server.create('eighth-resource', {
id: 141,
second_resource_id: 37
});
server.create('second-resource', {
id: 37,
first_resource_id: '11',
eighth_resource_ids: [140, 141]
});
server.create('first-resource', {
id: 11,
second_resource_ids: [36, 37]
});
first_resource model in mirage:
export default Model.extend({
third_resource_other_type: belongsTo(),
fourth_resource: belongsTo(),
fifth_resources: hasMany(),
second_resources: hasMany()
});
Let's try to focus a single relationship, since there's a lot going on in the question you've posted. We'll look at second-resource.
It looks like Mirage is sending back second_resource_ids under the attributes key of the first_resource primary data in the JSON:API payload. That tells me Mirage thinks second_resource_ids is an attribute of first_resource, when in fact it's a relationship.
Assuming your Models & Relationships are setup correctly, you need to tweak the way you're creating data in Mirage.
If you take a look at the Associations section of the Defining Routes guide, you'll see this message:
Mirage's database uses camelCase for all model attributes, including foreign keys (e.g. authorId in the example above)
Right now, you're doing this:
server.create('second-resource', {
id: 36,
first_resource_id: '11',
my_attribute: "my_attribute"
});
server.create('first-resource', {
id: 11,
second_resource_ids: [36, 37]
});
But from Mirage's perspective, you need to use camelCase IDs, or just pass in the relationships, to set these up correctly. Something like this:
let firstResource = server.create('first-resource', {
id: 11
});
server.create('second-resource', {
id: 36,
firstResource,
myAttribute: "my_attribute"
});
You could also pass in the foreign key on creation if you wanted - just be sure to use camelCase:
server.create('second-resource', {
id: 36,
firstResourceId: '11',
myAttribute: "my_attribute"
});
Just remember that the formatting decisions for things like attributes and foreign keys (things like some-attribute vs. some_attribute or relationship-id vs. relationship_id) are made at the serializer layer. When dealing with Mirage's ORM and database, you want to stick to camelCase, regardless of the format your Serializer emits.
For more information, have a look at these sections from the docs:
"Associations and serializers" section of the Quickstart
Defining relationships
"Working with relationships" section of the Factories guide

multiple relations using same model type in ember data

I have an account model that has the following:
export default Model.extend({
primaryStaff: belongsTo('staff'),
secondaryStaff: belongsTo('staff')
});
primaryStaff maps to the primaryStaffId key on the account model and secondaryStaff maps to secondaryStaffId. Is there a way to allow these to both point to the staff model?
Not having any luck. Thanks!
Update:
I'm using the JSON API Adapter -- here's a sample payload:
{
"data": {
"type": "account",
"id": "17",
"attributes": {
"businessId": 1,
"userId": 22,
"scopes": [
"customer",
"customer-22"
],
"keyCode": null,
"lockboxCode": null,
"notes": null,
"active": false,
"createdAt": "2017-01-31T20:13:39.465Z",
"updatedAt": "2017-02-20T03:49:17.308Z",
},
"relationships": {
"business": {
"data": {
"type": "business",
"id": "1"
}
},
"customer": {
"data": {
"type": "customer",
"id": "22"
}
},
"secondaryStaff": {
"data": null
},
"primaryStaff": {
"data": {
"type": "staff",
"id": "1"
}
}
}
}
}
You need to modify application (or model) serializer.
Please take a look at this twiddle

Ember: Access sideloaded model relationship data in template

I am trying to display a model's relationships in a template from sideloaded data, but there seems to be some problem. With Ember Inspector, I see that the relationships are correctly loaded from the data. However, the data is not displayed on the page.
Looking for solutions or suggestions on where to start debugging. Much appreciated.
Handlebars:
<dt>Categories</dt>
<dd>
<ul>
{{#each model.categories as |category| }}
<li>{{ category.name }}</li>
{{/each}}
</ul>
</dd>
The route:
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model(params) {
return this.store.findRecord('datasheet', params.id);
}
});
The models:
// app/models/datasheet.js
export default DS.Model.extend({
name: DS.attr('string'),
name_en: DS.attr('string'),
news: DS.attr('string'),
news_en: DS.attr('string'),
basic_information: DS.attr('string'),
basic_information_en: DS.attr('string'),
id_gradient_default: DS.attr('string'),
icon_name: DS.attr('string'),
icon_color: DS.attr('string'),
order: DS.attr('string'),
item_count: DS.attr('string'),
categories: DS.hasMany('category')
});
// app/models/category.js
export default DS.Model.extend({
name: DS.attr('string')
});
This is the JSON returned from the adapter method:
{
"data": {
"type": "datasheet",
"id": "21",
"attributes": {
"name": "Projekty",
"name_en": "Projects",
"news": "",
"news_en": "",
"basic_information": "",
"basic_information_en": "",
"id_gradient_default": "27",
"icon_name": "pin_flag",
"icon_color": "",
"order": "14"
},
"relationships": {
"categories": ["18", "19", "20", "51", "52"]
}
},
"included": [{
"type": "category",
"id": "18",
"attributes": {
"name": "Project"
}
}, {
"type": "category",
"id": "19",
"attributes": {
"name": "Activity"
}
}, {
"type": "category",
"id": "20",
"attributes": {
"name": "Project phase"
}
}, {
"type": "category",
"id": "51",
"attributes": {
"name": "Program"
}
}, {
"type": "category",
"id": "52",
"attributes": {
"name": "Milestone"
}
}]
}
Ember Inspector screenshot:
This is not correct JSONAPI:
"relationships": {
"categories": ["18", "19", "20", "51", "52"]
}
This is the correct JSONAPI equivalent:
"relationships": {
"categories": {
data: [{
id: '18',
type: 'category'
},{
id: '19',
type: 'category'
},{
id: '20',
type: 'category'
},{
id: '51',
type: 'category'
},{
id: '52',
type: 'category'
}]
}
}
So your data are loaded but not correctly linked. you can see this in the ember-inspector when you check the categories relationship.

How to display attributes of belongsTo object in Ember.js template

In my Ember app, a survey belongsTo a user; a user hasMany surveys. In my template, I would like to display a list of surveys, and the name of the user that created them. For now, I am pushing side-loaded data into the store via the application route, and it is showing up in the ember inspector->Data. The survey info is displaying correctly in the template, but the corresponding user's firstName will not appear. Help/guidance appreciated.
survey.js (model)
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user', {async: true}), //tried without async as well
title: DS.attr(),
post: DS.attr()
});
user.js (model)
import DS from 'ember-data';
export default DS.Model.extend({
surveys: DS.hasMany('survey', {async: true}),
firstName: DS.attr()
});
application.js (application route)
export default Ember.Route.extend({
model() {
this.store.push({
data: [{
id: 1,
type: 'survey',
attributes: {
title: 'My First Survey',
post: 'This is my Survey!'
},
relationships: {
user: 1
}
}, {
id: 2,
type: 'survey',
attributes: {
title: 'My Second Survey',
post: 'This is survey 2!'
},
relationships: {
user: 1
}
}, {
id: 1,
type: 'user',
attributes: {
firstName: 'Tyler'
},
relationships: {
surveys: [1, 2]
}
}]
});
}
});
surveys.js (route)
export default Ember.Route.extend({
model () {
return this.store.findAll('survey');
}
});
surveys.hbs (template)
<ul>
{{#each model as |survey|}}
<li>
<strong>{{survey.title}}</strong> //This works
<br>
{{survey.post}} //This works
<br>
Author: {{survey.user.firstName}} //This does not work
</li>
{{/each}}
</ul>
SOLUTION - updated application.js
export default Ember.Route.extend({
model() {
this.store.push({
"data": [ //Added double quotes throughout to conform to documentation
{
"id": "1",
"type": "survey",
"attributes": {
"title": "My First Survey",
"post": "This is my Survey!"
},
"relationships": {
"user": {
"data": {
"id": "1",
"type": "user"
}
}
}
}, {
"id": "2",
"type": "survey",
"attributes": {
"title": "My Second Survey",
"post": "This is survey 2!"
},
"relationships": {
"user": {
"data": {
"id": "1",
"type": "user"
}
}
}
}
],
"included": [
{
"id": "1",
"type": "user",
"attributes": {
"firstName": "Tyler"
} //no need to include user's relationships here
}
]
});
}
});
Payload relationship part is not correct. Should be:
relationships: {
user: {
data: {
id: 1,
type: 'user'
}
}
}
Also I think "user" payload should be in "included" section.
JSONAPISerializer api

Trouble consuming json rest data in ember-data

I'm trying to parse a json dataset in my ember data models but this throws an error in het console:
Uncaught TypeError: Cannot call method '_create' of undefined
DS.Store.Ember.Object.extend.materializeRecord
DS.Store.Ember.Object.extend.findByClientId
What am I doing wrong here?
This is the data I receive from the server:
{
"newsitems": [
{
"date": "2013-02-10T15:00:00+01:00",
"id": "1",
"images": [
{
"id": "1",
"value": "image.JPG"
},
{
"id": "3",
"value": "anotherimage.jpg"
}
],
"slug": "some-slug",
"summary": "some summary",
"text": "some text",
"thumb": {
"id": "2",
"value": "someimage.JPG"
},
"title": "Some title",
"type": "1",
"videos": [
{
"id": "AEOpX8tmiUI",
"value": "AEOpX8tmiUI"
},
{
"id": "kxopViU98Xo",
"value": "kxopViU98Xo"
}
]
}
]
}
These are my models:
App.NewsitemThumb = DS.Model.extend({
value: DS.attr('string'),
newsitem: DS.belongsTo('App.Newsitem')
});
App.NewsitemImage = DS.Model.extend({
value: DS.attr('string'),
newsitem: DS.belongsTo('App.Newsitem')
});
App.NewsitemVideo = DS.Model.extend({
value: DS.attr('string'),
newsitem: DS.belongsTo('App.Newsitem')
});
App.Newsitem = DS.Model.extend({
slug: DS.attr('string'),
type: DS.attr('string'),
title: DS.attr('string'),
summary: DS.attr('string'),
text: DS.attr('string'),
date: DS.attr('date'),
thumb: DS.belongsTo('App.NewsitemThumb'),
images: DS.hasMany('App.NewsitemImage'),
videos: DS.hasMany('App.NewsitemVideo')
});
For the record, any suggestions for optimizing these models are welcome. It feels so weird to make 3 models for video, images and a thumb.
According to this issue, this error pops up when you don't specify an explicit mapping for a hasMany relationship in your adapter.
Try defining your store as
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.RESTAdapter.extend({
serializer: DS.RESTSerializer.extend({
init: function() {
this._super();
this.map("App.Newsitem", {
images: { embedded: "load" },
videos: { embedded: "load" }
});
}
})
})
});