I have a slightly peculiar problem with loading my tree structure into Ember.
My models are:
book.js
- parts: DS.hasMany('part', {inverse: 'book', async: true})
part.js
- subparts: DS.hasMany('part', {inverse: 'parent_part', async: true}),
With the following API responses:
GET /api/books:
{
books: [
{id: 1, links: {parts: "/api/books/1/parts"}},
...
]
}
GET /api/books/1/parts:
{
parts: [
{
id: 1,
subparts: [10, 11]
},
{
id: 2,
subparts: []
}
]
}
The problem is in the tree nature of the parts: The book only has direct descendants id 1 and 2, but these have sub-parts on their own.
The structure as it is works but results in multiple sub-queries for each part that was not included in the /books/1/parts result. I want to avoid these queries, not only because of performance reasons but also because I will need additional query parameters which would get lost at this step... I know about coalesceFindRequests but it introduces new problems.
To rephrase the problem, Ember Data thinks that every part that is included in the /books/1/parts response should be added directly to the book:parts property. How can I still load all records of the parts tree at the same time?
I tried renaming the fields, but Ember Data assigns the records based on the model name, not the field name.
I fear that some creative adapter overriding will be necessary here. Any idea appreciated. The backend is completely under my control, so I could change things on that end, too.
You need to use a process called sideloading, which should work as you expect (I've had issues in the past with sideloading data). As mentioned in this issue, you want to split your parts into two separate arrays.
{
// These are the direct children
"parts": [{...}, {...}],
// These are the extra records
"_parts": [{...}, {...}]
}
Related
I have successfully managed to get this rather ember-unfriendly API result into a parent/child pair of models called 'connector' and 'pin', where the connector is the parent and an array of pins is the children. I have a hasMany('pin') on the connector model and belongsTo('connector') on the pins.
{
"Connector" : {
"ConnectorID" : "2015-11-30T16:34:34.217",
"ConnectorName" : "D38999/20WA98SN"
},
"Pins" : [{
"ConnectorID" : "2015-11-30T16:34:34.217",
"PinName" : "A"
}, {
"ConnectorID" : "2015-11-30T16:34:34.217",
"PinName" : "B"
}, {
"ConnectorID" : "2015-11-30T16:34:34.217",
"PinName" : "C"
}
]
}
So far, all is well, I think. I am now faced with getting all of the data from both to appear on a route called 'connector'. I can't quite wrap my mind around how to chain the promises so that I can get both
this.get('store').findRecord('connector', params.connector_id);
and
this.get('store').findRecord('connector', params.connector_id).findAll(???);
It seems like I am fighting an up-hill battle on this relationship. I wish I could just get Ember to treat the array of pins as it would any other singular data type and get/save the data with the record. Am I think of this correctly?
The answer to "I wish I could just get Ember to treat the array of pins..." comment was solved with
ember g transform array
Tips to this post:
How to represent arrays within ember-data models?.
I am pretty happy with the final code after I cleaned up all of my experiments. I didn't have to call
App.register("transform:array", DS.ArrayTransform);
At least I didn't have to write the call myself.
When a Handsontable is instantiated, it calls a recursive method to build a data schema: https://github.com/handsontable/handsontable/blob/be8654f78ca84efc982047ca6b399e6c6d99f893/src/dataMap.js#L28, which in turns calls objectEach: https://github.com/handsontable/handsontable/blob/master/src/helpers/object.js#L235-L245
However, with an Ember Data record, it tries to iterate over properties like store, which means it gets caught in an endless loop.
Is there any way to bypass the recursiveDuckSchema method?
Unless Handsontable has some interface to allow pre-parsing data before it reaches the core of the plugin, I would say you may have better luck by transforming your ember-data models into something handsometable understands.
let queryParams = //Your query params
let data = this.get('getTheContent'); //Your models
let handsomeData = data.map(function(item, index, enumerable)){
return { id: item.get('id'), name: item.get('name'), other: item.get('other') }
};
// Result is [{id: 1, name: 'John', other: 'Other'}, {...}]
Wrapping another javascript library to use with Ember bindings, etc, seems like an ordinary thing to do, but I haven't found much discussion of it.
I want to filter an ember record array using distance and travel time from the Google Maps Distance Matrix
service. I'm just not sure where in the application to encapsulate Google's javascript. Note: this is not a question about embedding a google map, it's about getting data into ember that doesn't come from a rest/json or fixtures as in all the tutorials and examples I've found.
Would people typically do this in the controller or create new models/adapters to get benefits from store caching? Or is there another way?
update: in case that's too vague, consider this: 20 records (with a google map component etc) listed by an array controller, a text field where the user types in a home address, a couple of other inputs where they set a maximum time or distance, and a search button which filters the listed records by comparing the user requirements with the result of querying the distance matrix for the home address to the 20 records' addresses, only showing the ones close enough to their home.
Use of the service in an application that doesn't display a Google map is prohibited.
So,the question is really about integrating a Google map to an Ember app.
Without any doubt you'll have to add the Google JS like in any other HTML project with:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MYSECRETKEY"></script>
So, the API is in global space and you just use it whenever you need it. Mostly all that will happen in your views, so you could wrap everything in a component. (I'm assuming that all relevant data has been passed from the controller to the view, it all depends on the design of your app.)
The following works, but it seems like it should be in the model/store/adapter layer.
App.DistanceController = Ember.Controller.extend
origin: (->
data = #get('data')
data.origin if data
).property('data')
destinationDistances: (->
data = #get('data')
data.distances if data
).property('data')
data: ((key, value)->
if arguments.length > 1
value
else
_this = this
value = null
service = new google.maps.DistanceMatrixService()
service.getDistanceMatrix(
origins: ["London, England"],
destinations: [
"Bristol, England",
"Edinburgh, Scotland",
"Leeds, England",
"Liverpool, England",
"Manchester, England",
"Newcastle, England",
"Nottingham, England",
"York, England"
],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
, (response, status) ->
if (status == google.maps.DistanceMatrixStatus.OK)
distances = []
for destination, n in response.destinationAddresses
distances.push {
destination: destination
distance: response.rows[0].elements[n].distance.text
}
_this.set('data', {
origin: response.originAddresses[0]
distances: distances
})
)
value
).property()
kudos #rlivsey https://stackoverflow.com/a/20623551/395180
all new jsfiddle: http://jsfiddle.net/vJxvc/2/
Currently, i query an api that will return JSON like this. The API cannot be changed for now, which is why I need to work around that.
[
{"timestamp":1406111961, "values":[1236.181, 1157.695, 698.231]},
{"timestamp":1406111970, "values":[1273.455, 1153.577, 693.591]}
]
(could be a lot more lines, of course)
As you can see, each line has a timestamp and then an array of values. My problem is, that i would actually like to transpose that. Looking at the first line alone:
{"timestamp":1406111961, "values":[1236.181, 1157.695, 698.231]}
It contains a few measurements taken at the same time. This would need to become this in my ember project:
{
"sensor_id": 1, // can be derived from the array index
"timestamp": 1406111961,
"value": 1236.181
},
{
"sensor_id": 2,
"timestamp": 1406111961,
"value": 1157.695
},
{
"sensor_id": 3,
"timestamp": 1406111961,
"value": 698.231
}
And those values would have to be pushed into the respective sensor models.
The transformation itself is trivial, but i have no idea where i would put it in ember and how i could alter many ember models at the same time.
you could make your model an array and override the normalize method on your adapter. The normalize method is where you do the transformation, and since your json is an array, an Ember.Array as a model would work.
I am not a ember pro but looking at the manual I would think of something like this:
a = [
{"timestamp":1406111961, "values":[1236.181, 1157.695, 698.231]},
{"timestamp":1406111970, "values":[1273.455, 1153.577, 693.591]}
];
b = [];
a.forEach(function(item) {
item.values.forEach(function(value, sensor_id) {
b.push({
sensor_id: sensor_id,
timestamp: item.timestamp,
value: value
});
});
});
console.log(b);
Example http://jsfiddle.net/kRUV4/
Update
Just saw your jsfiddle... You can geht the store like this: How to get Ember Data's "store" from anywhere in the application so that I can do store.find()?
at the moment, when ember is asking for child data through the rest adapater, it makes a GET request with the following options:
http://localhost/orders?ids%5B%5D=0x0000000000000386&ids%5B%5D=0x00000000000003a4&ids%5B%5D=0x00000000000003cf&ids%5B%5D=0x0000000000000631&ids%5B%5D=0x0000000000000639
which equates to parameters of
ids[]:0x0000000000000386
ids[]:0x00000000000003a4
ids[]:0x00000000000003cf
ids[]:0x0000000000000631
ids[]:0x0000000000000639
I was wondering if there was a way of changing that to be either
id1:0x0000000000000386
id2:0x00000000000003a4
id3:0x00000000000003cf
id4:0x0000000000000631
id5:0x0000000000000639
or
{ids: [{"id":"0x0000000000000386"},
{"id":"0x00000000000003a4"},
{"id":"0x00000000000003cf},"
{"id":"0x0000000000000631"},
{"id":"0x0000000000000639"}
]}
I have solved this by using the "links" option in the data.
Within the json returned at the higher level , include the links
{customers : [
{name": "foobar inc",
"links": {"orders:/customers/181/orders"}
}]
}
so now when ember tries to get the orders of a customer, it will make a json request to the url specified in the links
this works really well for me. It also has the advantage of not having to load all children in as either ids[] or sideloading.