I'm using Ember 2.4.1 and trying to build the hierarchical tree with self reference model.
Here is the my Ember model
// app/models/category.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
parent: DS.belongsTo('category', { inverse: 'children' }),
children: DS.hasMany('category', { embedded: 'always', async: false, inverse: 'parent' })
});
And server response in route /categories with embedded data (I use RESTAdapter on Ember side):
{"categories":[
{
"id":4,
"name":"Root element w/o children",
"type":"Category",
"children":[]
},
{
"id":5,
"name":"Root element with a child",
"type":"Category",
"children":[
{
"id":6,
"name":"A child",
"type":"Category",
"children":[]
}
]
}
]}
As you can see Category with id 5 has a child with id 6 and it embedded. But while Ember loading the page it makes an error: Assertion Failed: You looked up the 'children' relationship on a 'category' with id 5 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (DS.hasMany({ async: true }))
If I include the category with id 6 in JSON-root like {categories: [{id:4, …}, {id:5, …}, {id:6, …}]} error will disappear but I don't know why I need embedding in this case. May be I don't understand how embedding works in Ember.
So I'd like to ask advice how to make properly work Ember Data with embedded response without duplicating it and without async: true.
UPD #TheCompiler answered on my question in comments. Adding serializer with mixin solve my problem:
// app/serializers/category.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
children: { embedded: 'always' }
}
});
No need to duplicate the record. The Rest Adapter just doesn't play nice with nested JSON objects. Try formatting the data like this:
{"categories":[
{
"id":4,
"name":"Root element w/o children",
"type":"Category",
"children":[]
},
{
"id":5,
"name":"Root element with a child",
"type":"Category",
"children":[6]
},
{
"id":6,
"name":"A child",
"type":"Category",
"children":[]
}
]}
Related
I have 2 API's:
http://example.api.com/api.json (this file have aprox 5mb)
http://api.com/:itemId
The 1st one have all data that i need, like this:
{
"realms": [
{"name":"Azralon","slug":"azralon"}],
"auctions": [
{"auc":828911977,"item":76139,"owner":"Bloodkina","bid":15294990,"buyout":16099990,"quantity":10,"timeLeft":"VERY_LONG"},
{"auc":828911979,"item":10000,"owner":"Bloodkina", "bid":15294990,"buyout":16099990,"quantity":100,"timeLeft":"VERY_LONG"},
{"auc":829305192,"item":98828,"owner":"Tempestivå","bid":15294990,"buyout":16099990,"quantity":5,"timeLeft":"VERY_LONG"},
{"auc":829305193,"item":98728,"owner":"Tempestivå", "bid":15294990,"buyout":16099990,"quantity":2,"timeLeft":"VERY_LONG"}
]}
The 2nd one have the name of the Items, but it only responds when i pass itemId as parameter. For example the item:76139, like http://api.com/76139
{
"id": 76139,
"description": "",
"name": "Wild Jade",
"icon": "inv_misc_gem_x4_rare_uncut_green",
}
I want to show the name of item and owner, but i getting an error like <DS.PromiseObject:ember71726> im my item field, the owner field is ok. How can i do this?? (it's the Blizzard API for auctions and items)
model/auction.js
import DS from 'ember-data';
export default DS.Model.extend({
auc: DS.attr('number'),
item: DS.belongsTo('item'), //items: DS.belongsTo('item'),
owner: DS.attr('string'),
});
model/item.js
import DS from 'ember-data';
export default DS.Model.extend({
auctions: DS.hasMany('auction'),
name: DS.attr('string')
});
routes/index.js
import Route from '#ember/routing/route';
export default Route.extend({
model(){
return this.store.findAll('auction');
}
});
routes/item.js
import Route from '#ember/routing/route';
export default Route.extend({
model(params){
return this.store.findRecord('item', params.item_id)
},
});
serializers/auction.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeResponse (store, primaryModelClass, payload, id, requestType) {
return {
realms: payload.realms,
data: payload.auctions.map(ah=>{
return {
id: ah.auc,
type:'auction',
attributes: ah,
//Added this
relationships: {
item:{
data: {
id: ah.item,
type: 'item',
}
}
}
}
})
};
}
});
serializers/item.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalizeResponse (store, primaryModelClass, payload, id, requestType) {
payload = {
data : payload,
id: payload.id,
name: payload.name
};
return this._super(store, primaryModelClass, payload, id, requestType)
}
});
templates/index.hbs
{{#each model as |auction|}}
<ul>
<li>{{auction.items.name}}</li>
<li>{{auction.quantity}}</li>
<li>{{auction.bid}}</li>
<li>{{auction.buyout}}</li>
<li>{{auction.timeLeft}}</li>
<li>{{auction.owner}}</li>
</ul>
{{/each}}
Hey Cas 👋 I'm going to try and answer this one as best I can while trying to describe some of the issues that you were probably facing along the way. I have it working locally so hopefully I am going to be able to communicate how you can get it working on your side.
Firstly, as I mentioned in my comment you seemed to have a missmatch between your API, your model and your template when it came to how you were referencing items. You need to make sure that each key is correct so they all match up. Here is my backend responder, my model and my template:
Backend responder using express-autoroute:
module.exports.autoroute = {
get: {
'/auctions': function getThings(req, res) {
res.json({
realms: [{
name: 'Azralon',
slug: 'azralon',
}],
auctions: [{
auc: 828911977,
item: 76139,
owner: 'Bloodkina',
bid: 15294990,
buyout: 16099990,
quantity: 10,
timeLeft: 'VERY_LONG',
},
...
});
},
},
};
Auction model (Ember)
import DS from 'ember-data';
export default DS.Model.extend({
auc: DS.attr('number'),
item: DS.belongsTo('item'),
owner: DS.attr('string'),
});
Application template (Ember)
{{#each model as |auction|}}
<ul>
<li>{{auction.item.name}}</li>
<li>{{auction.quantity}}</li>
<li>{{auction.bid}}</li>
<li>{{auction.buyout}}</li>
<li>{{auction.timeLeft}}</li>
<li>{{auction.owner}}</li>
</ul>
{{/each}}
As you can see the backend is responding with item as an attribute to an auction, the model is using item as it's attribute name and the template is also accessing the key item. This is what I meant when I said they needed to match 🙂
The second thing that I noticed is that your auction serialiser isn't saying anything about relationships. If you check out the JSON:API spec you will see how relationships are supposed to be defined, i.e. with a relationships object
I was able to get your thing working using the following code:
Auction Serializer (Ember)
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
normalizeResponse (store, primaryModelClass, payload, id, requestType) {
return {
realms: payload.realms,
data: payload.auctions.map(ah => {
return {
id: ah.auc,
type:'auction',
attributes: ah,
relationships: {
item: {
data: {
id: ah.item,
type: 'item',
}
}
}
}
})
};
}
});
as you can see I'm building the relationships object and making sure that the item key matches.
The last issue I found was that your item serialiser wasn't working, I'm assuming that this is just that you didn't get this far because you successfully implemented the Auction Serializer. Here is my implementation:
Item Serializer (Ember):
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
normalizeResponse (store, primaryModelClass, payload, id, requestType) {
return {
data : {
attributes: payload,
id: payload.id,
type: 'item',
},
};
}
});
As I said this is now working for me locally but let me know if you have any more issues 🙂
I'm currently writing tests for my App written with EmberJS. I'm using Mirage.
I have the two following models:
mirage/models/paperwork.js
export default Model.extend({
customer: belongsTo('customer'),
paperwork_products: hasMany('paperwork-product', { inverse: 'paperwork' }),
mirage/models/paperwork-product.js
export default Model.extend({
paperwork: belongsTo('paperwork', { inverse: 'paperwork_products' }),
});
In my scenario, I'm creating my datas like this:
const paperwork = server.create('paperwork');
const paperworkProduct = server.create('paperwork-product', { paperwork });
paperwork.paperwork_products.add(paperworkProduct);
My route:
export default ApplicationRoute.extend({
model(params) {
return this.store.findRecord('paperwork', params.paperwork_id, { include: 'paperwork_products' }),
},
});
The problem is that I can't access paperwork.paperwork_products in my template. It's undefined (other paperwork attributes are here, but not relationship). I already even tried to put a debugger in my mirage/config.js when routes are declared. My paperwork exists, and his "paperwork_products" too. But I can't get paperwork_products data in my template.
What am I doing wrong ? I think I must change something in my :
this.get('v1/paperworks/:id');
But I don't know what ...
Thanks in advance !
Edit: Here are my real Ember models:
models/paperwork.js
export default DS.Model.extend({
customer: DS.belongsTo('customer'),
paperwork_products: DS.hasMany('paperwork-product', { async: true }),
});
models/paperwork-product.js
export default DS.Model.extend({
paperwork: DS.belongsTo('paperwork'),
});
Yesterday I tried to compare the real JsonApi response from my back, and Mirage response, and I saw that in the relationships hash, my relationship "paperwork_products" was changed to paperwork-products (with Mirage). So there is a problem with relationships with an underscore or models with dash ...
In config.js, I tried to mock JSONAPI Backend, and it works wells. Just replaced "paperwork-products" by "paperwork_products"
Mirage response :
"relationships":{
"customer":{
"data":{
"type":"customers",
"id":"1"
}
},
"paperwork-products":{
"data":[
{
"type":"paperwork-products",
"id":"1"
}
]
}
}
Should be :
"relationships":{
"customer":{
"data":{
"type":"customers",
"id":"1"
}
},
"paperwork_products":{
"data":[
{
"type":"paperwork_products",
"id":"1"
}
]
}
}
My other models with hasMany relationships do not have any problems.
To confirm, do you have Ember Data models setup with the same relationships? Without those, things may. It work very well ...
If you do, could you post those models as well?
Also, as an FYI, Mirage 0.3.0 comes with an auto-sync setup that will read your Ember Data models and create corresponding Mirage models without any work. It's been lovely ...
Edit:
I would suggest you rework your Ember Data model to use camel cased relationships. If you do the following:
models/paperwork.js
export default DS.Model.extend({
customer: DS.belongsTo('customer'),
paperworkProducts: DS.hasMany('paperwork-product', { async: true }),
});
I would expect it to work without issue, as Ember Data automatically translates camelCased relationships to the appropriate JSON-API key
Does that work for you?
I am using Ember 1.13.2 and Ember Data 1.13.4. The API conforms to JSON API format (http://jsonapi.org/format).
A user has many items. Doing {{model.items}} in the template will return ALL items of the user.
What if I also need to display ONLY blue items from the user. How should I go about this?
// Route
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
// Executes: http://localhost:3099/api/v1/users/5
return this.store.findRecord('user', params.user_id);
}
})
// Template
firstName: {{model.firstName}} - works
<br>items: {{model.items}} - works
<br>blue items: {{model.items}} - what do we do about this?
// app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
items: DS.hasMany('item', { async: true }),
firstName: DS.attr('string')
});
// app/models/item.js
import DS from 'ember-data';
export default DS.Model.extend({
user: DS.belongsTo('user', { async: true }),
name: DS.attr('string')
});
I misunderstood the original question. It seems as if you want to fetch only the items where the color is blue (and avoid fetching the rest). For this, you'll need to query the server, which requires server-side code. But, once you have the server-side code done, you can do something like this:
blueItems: Ember.computed('items.#each.color', {
get() {
const query = {
user: this.get('id'),
color: 'blue'
};
return this.get('store').find('item', query);
}
})
But again, you'll need your server to support querying for that data. (The JSON API states how you need to return the data, but you'll need to implement the query yourself.)
Old answer that filters the items after fetching for display (just for reference):
I would use a computed property:
blueItems: Ember.computed('items.#each.color', {
get() {
return this.get('items').filter((item) => {
return item.get('color') === 'blue';
});
}
})
Or the shorthand ;)
blueItems: Ember.computed.filterBy('items', 'color', 'blue')
Not every operation has an Ember shorthand which is why I gave the full example first.
Using computed properties with promises is sometimes tricky, but this computed property should update whenever your items array updates.
I am having a hard time to understand how the model relationships works in ember-data. I understand the concept one to many or one to one or many to many, but I don't understand how to use it properly..
My API is sending me this data :
{
gameweek: [
{
commonID: '23',
content: 'blablabla',
game: [
{
commonID: '23',
gameID: 4,
title: 'first game'
},
{
commonID: '23',
gameID: 8,
title: 'second game'
}
]
},
{
commonID: '24',
content: 'blebleble'
game: [
{
commonID: '24',
gameID: 12,
title: 'another game'
}
]
}
]
}
As you can see I receive an array that contain some data and an other array.
I don't really know if how I should create my models, should I have just one model ? or multiple like this ? (correct me if its wrong) :
//gameweek.js
import DS from "ember-data";
export default DS.Model.extend({
commonID: DS.attr('string'),
title: DS.attr('string'),
games: DS.hasMany('game')
});
//game.js
import DS from "ember-data";
export default DS.Model.extend({
commonID: DS.attr('string'),
title: DS.attr('string'),
gameweek: DS.belongsTo('gameweek')
});
I would like to be able to save my arrays in the store and keep the relationships between them.
If I do a this.store.find('gameweek', {commonID: '23'} ); I would like to get also all of the game that are related the gameweek. (the commonID would be the same if they are related).
Do I have to create a custom serializer ?
So many questions, thanks for you help !
=============================
UPDATE :
I tried to extend the DS.RESTSerializer like this :
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
extractArray: function( store, type, record ) {
var gameweek = record.predictions;
gameweek.forEach(function( entry ) {
var data = entry.games.map(function(game) {
return game.gameID;
});
entry.games = data;
});
record = { prediction: gameweek };
return this._super( store, type, record );
}
});
This is mainly replacing my game array by an array of gameID, the new array looks like this :
{
gameweek: [
{
commonID: '23',
content: 'blablabla',
game: ["4", "8"]
},
{
commonID: '24',
content: 'blebleble'
game: ["12"]
}
]
}
But I get this error :
Error: Assertion Failed: Unable to find transform for 'integer'
I am not sure what to do here.
===================================
UPDATE2:
I tried this too :
//serializers/gameweek.js
import DS from "ember-data";
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
primaryKey: 'gameWeekID',
attrs: {
game: { embedded: 'load' }
},
extractArray: function( store, type, record ) {
// The array of object isn't at the root structure of the record
var record = record.predictions;
record = { prediction: record };
return this._super( store, type, record );
}
});
//serializers/game.js
import DS from "ember-data";
export default DS.RESTSerializer.extend({
primaryKey: 'gameID'
});
I got this error :
Error: Assertion Failed: Ember Data expected a number or string to represent the record(s) in the "games" relationship instead it found an object. If this is a polymorphic relationship please specify a "type" key. If this is an embedded relationship please include the "DS.EmbeddedRecordsMixin" and specify the "games" property in your serializer's attrs object.
In ember you dont save arrays as models you save objects as models. Ember data expects data back in a certain way so you will need to either do this server side or do it with a serializer.
You can save relationships no problem if your models are set clearly.
In the code below taken from embers site your model is a post. so when you query for a post this is what should be returned. The post has a relationship with comments. posts have many comments and comments belong to posts. In the post model there is the id for each comment that is related to that post and then the comments are included as a separate array. http://guides.emberjs.com/v1.12.0/models/the-rest-adapter/#toc_sideloaded-relationships
{
"post": {
"id": 1,
"title": "Node is not omakase",
"comments": [1, 2, 3]
},
"comments": [{
"id": 1,
"body": "But is it _lightweight_ omakase?"
},
{
"id": 2,
"body": "I for one welcome our new omakase overlords"
},
{
"id": 3,
"body": "Put me on the fast track to a delicious dinner"
}]
}
The related model files for the above structure are
app/models/post.js
export default DS.Model.extend({
title: DS.attr('string'),
comments: DS.hasMany('comment')
});
app/models/comment.js
export default DS.Model.extend({
body: DS.attr('string'),
post: DS.belongsTo('post')
});
I dont know if its just my head or its the end of the day but the above naming and structure layout is very confusing. Can you include a bit more detail or make the details less generic, it might help with trying to figure the data out.
You should have separate models for gameweek and game. Ember Data works better with more granular models, rather than trying to deal with model fields which are raw objects. This will make it easy to extend the game model in the future with additional functionality, such as computed properties and validators. So your proposed model structure is fine.
To make this work with your current JSON structure, however, you're going to have to declare that game is embedded. To do that
// serializers/gameweek.js
import ApplicationSerializer from './application';
import DS from 'ember-data';
export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
games: { embedded: 'load' }
}
});
We inherit from ApplicationSerializer as best practice so that if it specifies things they are inherited by this model-specific serializer.
In addition, Ember Data is going to insist on a unique id for each game, so it has a way to identify it in the store. If gameId is unique, you can use that as is, but you'll have to let Ember Data know, by saying
// serializers/game.js
import ApplicationSerializer from './application';
import DS from 'ember-data';
export default ApplicationSerializer.extend({
primaryKey: 'gameId'
});
Once you do this, you will no longer refer to the id as gameId; you will refer to it as id, and you do not need to, and should not, declare it as part of your model.
Pardon me for coming up with this title but I really don't know how to ask this so I'll just explain.
Model: Group (has) User (has) Post
Defined as:
// models/group.js
name: DS.attr('string'),
// models/user.js
name: DS.attr('string'),
group: DS.belongsTo('group')
// models/post.js
name: DS.attr('string'),
user: DS.belongsTo('user'),
When I request /posts, my server returns this embedded record:
{
"posts": [
{
"id": 1,
"name": "Whitey",
"user": {
"id": 1,
"name": "User 1",
"group": 2
}
}
]
}
Notice that the group didn't have the group record but an id instead.
With my serializers:
// serializers/user.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
group: {embedded: 'always'}
}
});
// serializers/post.js
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
user: {embedded: 'always'}
}
});
This expects that the User and Post model have embedded records in them. However, it entails a problem since in the json response doesn't have an embedded group record.
The question is, is there a way I can disable embedding records in the 3rd level?
Please help.
Here is a good article about serialization:
http://www.toptal.com/emberjs/a-thorough-guide-to-ember-data#embeddedRecordsMixin
Ember docs:
http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html
Basically, what it says is that you have 2 options 1) serialize and 2) deserialize. Those two have 3 options:
'no' - don't include any data,
'id' or 'ids' - include id(s),
'records' - include data.
When you write {embedded: 'always'} this is shorthand for: {serialize: 'records', deserialize: 'records'}.
If you don't want the relationship sent at all write: {serialize: false}.
The Ember defaults for EmbeddedRecordsMixin are as follows:
BelongsTo: {serialize:'id', deserialize:'id'}
HasMany: {serialize:false, deserialize:'ids'}