Ember-data: validation errors on relationships (hasMany) - ember.js

I'm trying to create record with associated records in one request. In case if some of nested records have validation errors, I'd like to access appropriate errors on that record. I'm using json-api adaptor, so what should be the format of errors from the backend? I'm trying something like this, with no luck though:
{"errors":[
{
"detail": "can't be blank",
"source": {
"pointer":"data/relationships/steps/0/data/attributes/est_threshold"
}
}
]}
According to this line, it should be implemented somehow:
https://github.com/emberjs/data/blob/master/addon/adapters/errors.js#L7
Any ideas?

You'll need to sideload nested records in the data. The example structure given in the ember guides is:
{
"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"
}]
}
https://guides.emberjs.com/v1.10.0/models/the-rest-adapter/

So it doesn't seem to be implemented yet. I found kinda hackish way to do that in the model mixin:
`import Ember from 'ember'`
RelatedErrors = Ember.Mixin.create
save: ->
#_super().catch (resp) =>
resp.errors.forEach (err) =>
if [_, rel, idx, attr] = err.source.pointer.match /^data\/relationships\/(\w+)\/(\d+)\/data\/attributes\/(\w+)$/
#get(rel).objectAt(idx).get('errors').add(attr, err.detail)
`export default RelatedErrors`
However, add on DS.Errors is deprecated, so this is still not a perfect solution. Also invalid state of related models need to be cleared before each commit, which is not happening this far.

Related

Recommended pattern to implement global Search with multiple Objects type (Ember 2 + JSONAPI)

I am new to Ember and I will like to implement a server side search endpoint that returns results for several models/tables in DB.
Trying to figure out what is the best practice to do this in Ember.
Server results can contain several types of objects/models, each model is already defined in ember-data.
So far I am able to retrieve the results (I can see the results in ember-inspector) but I am not able to render it properly (I only have access to first object for some reason).
Current architecture:
rails-5 server with JSONAPI response
ember 2.3 with multiple models
Flow:
POST /search with body:
{"search":{"query": "xxx","size": "10"}}
RESULT:
{
"data": [
{
"id": "111111",
"type": "foo",
"attributes": {
"x": "y"
}
},
{
"id": "222222",
"type": "bar",
"attributes": {
"z": "y"
}
}
]
}

How is a json paginated resource supposed to look like?

With Ember Data and Jsonapi. How is a json paginated resource supposed to look like?
I built my response so it looks like:
"meta": {
"page": {
"number": 1,
"size": 5,
"total": 39
}
},
"links": {
"self": "http://localhost:3099/api/v1/articles",
"prev": null,
"next": "http://localhost:3099/api/v1/articles?page[number]=2",
"first": "http://localhost:3099/api/v1/articles?page[number]=1",
"last": "http://localhost:3099/api/v1/articles?page[number]=39"
},
"data": [
...
]
But I am not exactly sure if this is the right format. based on the explanation at http://jsonapi.org/format/#fetching-pagination
Or, are the pagination links (i.e. prev, next, first and last) supposed to be in meta.page ?
You could use ember-cli-pagination and its format to do pagination. I'm pretty sure Ember Data does not follow the JSON API spec strictly.
Based on your sample this could be a format:
{
"meta": {
"total_pages": 3,
"page": 1
},
"articles": [
{"id": 1, "title": "Hello World", "body": "More to Come"},
// ......
]
}
The request URL of this payload could be http://localhost:3099/api/v1/articles?page=1. See the API for more info.
Ember Data doesn't follow the JSON spec strictly so you should concentrate more on setting up the JSON with what ED needs. I would personally move the 'links' info into the meta tag. Otherwise Ember-Data will attempt to put them into a model called 'links', which may not be what you want. If you do intend to store those inside a separate 'links' model, then what you have is fine.

Ember - Only update fields returned in response JSON

we would like to add lazy loading functionality to our ember project, but it looks like ember will always override fields not returned by the response JSON with NULL. First I get a list of users:
GET https://example.com/users
{
"users": [
{
"id": 1,
"name": 'user1',
"email": 'email#user1.com',
"images": [],
"posts": []
},
{
"id": 2,
"name": 'user2',
"email": 'email#user2.com',
"images": [],
"posts": []
},
{
"id": 3,
"name": 'user3',
"email": 'email#user3.com',
"images": [],
"posts": []
},
]
}
This provides a minimal set of user information, with two empty hasMany relations "images" and "posts".
Now, if somebody want to see the users posts or images he would click a button which triggers the lazy loading:
GET https://example.com/userImages/1
{
"user": {
"id": 1,
"images": [1,2,3,4]
},
"images": [
{
"id": 1,
"name": "image1",
"path" "path/to/img1/"
},
{
"id": 2,
"name": "image2",
"path" "path/to/img2/"
},
{
"id": 3,
"name": "image3",
"path" "path/to/img3/"
},
{
"id": 4,
"name": "image4",
"path" "path/to/img4/"
}
]
}
To reduce traffic to a minimum, only the newly loaded information is included. After the adapter has deserialzed and pushed the new data to the store, all fields from User1 which are not included in the payload (name, email) are set to NULL in the ember store (tested with store.pushPayload('model', payload)).
Is there a possibility to update only incoming data? Or is there a common best practice to handle such a case?
Thanks in advance for your help
EDIT:
One possibility would be to extend the ember-data "_load()" function with the block
for (var key in record._data) {
var property = record._data[key];
if( typeof(data[key]) == 'object' && data[key] == null ) {
data[key] = property;
}
}
But this is the worst possible solution I can imagine.
I think what you want is the store's update method. It's like push (or pushPayload), except that it only updates the data that you give it.
Your property returns a promise and that promise returns whatever came back from the server.
foobar: function() {
return this.store.find('foobar');
}
When the promise resolves, you have two versions of the data, the one already rendered in the client (dataOld) and the one that just returned from the backend (dataNew). To update the client without removing what hasn't change, you have to merge the old and the new. Something along the lines of:
foobar: function() {
var dataOld = this.get('foobar');
return this.store.find('foobar').then(function(dataNew) {
return Ember.$.merge(dataOld, dataNew);
});
}

Side-loaded records request data that is already loaded

I use side-loading extensively in my Ember Data app to avoid making multiple round-trips to the API, and until now it has always worked out great.
I am using Ember 1.6.0-beta.3, Ember Data 1.0.0-beta.7, DS.ActiveModelAdapter, and DS.ActiveModelSerializer.
If I save a Foo model, which causes this request:
POST /foos
{
"foo": {
"name": "Foo"
}
}
The server responds with the created Foo, but also with a side-loaded Bar that references the new Foo.
201 Created
{
"foo": {
"id": 1,
"name": "Foo"
},
"bars": {
"id": 1,
"foo_ids": [1]
}
}
After this response, it appears that the Bar does not know that a Foo with ID=1 is in the store, and issues the following request:
GET /foos?ids[]=1
This request fails because I don't have that endpoint. I would not expect that Ember Data should send this request at all, because we just loaded the Foo with ID=1.
Instead, I would expect that no additional request should be made. Instead, the Bar should become associated with the newly created Foo.
Is my expectation out of line? Is this a bug?
EDIT
I was able to work around this issue by explicitly side-loading the foo. This is very inelegant, but hey, it's a work-around.
Specifically, I changed my API to respond with the following after a POST /foos:
{
"foo": {
"id": 1,
"name": "Foo"
},
"bars": {
"id": 1,
"foo_ids": [1]
},
"foos": [{
"id": 1,
"name": "Foo"
}]
}
Then the side-loaded Bar doesn't try to load it's Foo.
I'm going to leave this open, because a work-around is not a fix.

CRUD operations using Ember-Model

Here,I am trying to implement CRUD operations using ember-model.
I am totally new to ember environment,actually i don't have much understanding of ember-model.
Here,i am trying to add new product and delete existing one.I am using inner node of fixture
i.e. cart_items.My this fixture contains two node i.e. logged_in and cart_items and this what my fixture structure :
Astcart.Application.adapter = Ember.FixtureAdapter.create();
Astcart.Application.FIXTURES = [
{
"logged_in": {
"logged": true,
"username": "sachin",
"account_id": "4214"
},
"cart_items": [
{
"id": "1",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
},
{
"id": "2",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
},
{
"id": "3",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
}
]
}
];
I want to this fixture struture only to get data in one service call from server.
Now,here is my code which i am using to add and delete product from cart_items
Astcart.IndexRoute = Ember.Route.extend({
model: function() {
return Astcart.Application.find();
}
});
Astcart.IndexController = Ember.ArrayController.extend({
save: function(){
this.get('model').map(function(application) {
var new_cart_item = application.get('cart_items').create({name: this.get('newProductDesc'),qty: this.get('newProductQty'),price: this.get('newProductPrice'),subtotal: this.get('newProductSubtotal')});
new_cart_item.save();
});
},
deleteproduct: function(product){
if (window.confirm("Are you sure you want to delete this record?")) {
this.get('model').map(function(application) {
application.get('cart_items').deleteRecord(product);
});
}
}
});
But when i am trying to save product i am getting an exception
Uncaught TypeError: Object [object global] has no method 'get'
And when i am trying to delete product i am getting an exception
Uncaught TypeError: Object [object Object] has no method 'deleteRecord'
Here,i also want to implement one functionality i.e. on every save i need to check if that product is already present or not.
If product is not present then only save new product other wise update existing product.
But i don't have any idea how to do this?
I have posted my complete code here.
Can anyone help me to make this jsfiddle work?
Update
I have updated my code here with debugs.
Here, i am not getting any exception but record is also not getting delete.
I am not getting what is happening here?
Can anyone help me to make this jsfiddle work?
'this' context changes within your save method. You need to use the 'this' of the controller and not the map functions. Try this:
save: function(){
var self = this;
self.get('model').map(function(application) {
var new_cart_item = application.get('cart_items').create({
name: self.get('newProductDesc'),
qty: self.get('newProductQty'),
price: self.get('newProductPrice'),
subtotal: self.get('newProductSubtotal')
});
new_cart_item.save();
});
}