Fetch data from server in chunks using ember data (like infinite scroll) - ember.js

I would like to display a very long list of users (yes i suggested pagination but the client wont take it) and i would like to fetch a few records at a time.
This is mainly because creating the list on the server side is resource intensive (every field is encrypted in the database<-- again there is little i can do to change this) and retrieving 1000 records would slow down the app. so i would like to display 30 records and get the next 30 immediately afterwards (the same way infinite scroll works, without having to scroll down to fetch more records). Below is my route handler:
import Ember from 'ember';
export default Ember.Route.extend({
model(){
return this.store.query('user', {
firstname:'doe' // this comes from a textbox when filtering the list of users
pageSize:30,
page:1,
orderBy:'id'
});
}
});
To make ember and webapi play nice together, i have implemented everything here https://github.com/CrshOverride/ember-web-api
the api does not return any pagination information, but i would like to keep fetching the next page until the recordset that returns is smaller than pagesize.
Background: Im migrating from angular 1 to ember 2 (very much an ember novice) and i believe i am using ember data and i generate most stuff via ember-cli

This is something that Ember-Data doesn't provide out of the box, but is very easy to implement on your own.
// route.js
export default Ember.Route.extend({
setupController(controller) {
controller.fetchUsers(someNameOrAnother);
}
});
// controller.js
export default Ember.Controller.extend({
fetchUsers(name) {
this.set('allUsers', []);
this.fetchUsersHelper(name);
},
fetchUsersHelper(name, page = 1) {
const queryParams = {
firstname: name,
pageSize: 30,
page,
orderBy: 'id'
};
this.store.query('user', queryParams).then((users) => {
this.set('allUsers', this.get('allUsers').concat(users.toArray()));
if (users.get('length')>= queryParams.pageSize) {
this.fetchUsersHelper(name, queryParams.page + 1);
}
});
}
});

Related

Ember.js v2 Load multiple models in route without making separate requests

Just getting started with Ember.js, so after a workign myself through the various tutorials online for a couple of weeks(…), I really can't puzzle out the following question.
I want to display 4 models on 1 route. How can I do that, while avoiding making 4 server calls?
More inforamtion:
I want to display records of type "person", "quote", "product" and "case" on my index page.
In my index route, (routes/index.js) I can load them using:
import Ember from "ember";
export default Ember.Route.extend({
model(){
return Ember.RSVP.hash({
persons : this.get('store').findAll('person'),
quotes : this.get('store').findAll('quote'),
cases : this.get('store').findAll('case'),
products: this.get('store').findAll('product')
});
}
});
(And in my adapter, adapters/application.js, I have: )
import DS from "ember-data";
export default DS.JSONAPIAdapter.extend({
host : 'http://localhost:8080/dummy.php',
pathForType: function (type) {
return "?type=" + type;
}
});
This works very nicely :), but ember.js makes 4 requests:
However, I could easily provide a JSON file that provides records of all 4 types.
So, how can I tell ember.js:
"Here's a nice large JSON file, full of records. Now, use only records
of the 'person'-type for the person model, and idem dito for 'case',
'quote' and 'product'
?
Nothing wrong in loading model per request. If models are related then you should consider defining relationship between them. again for loading any async data it will make network request.
If you want to load data in single request for different model type, then you can try the below, this is not ember-data way. so I will not encourage this.
import Ember from "ember";
const {RSVP} = Ember;
export default Ember.Route.extend({
model() {
return RSVP
.resolve(Ember.$.getJSON('http://localhost:8080/dummy.php'))
.then((result) => {
this.get('store').pushPayload(result);
return {
persons : this.get('store').peekAll('person'),
quotes : this.get('store').peekAll('quote'),
cases : this.get('store').peekAll('case'),
products: this.get('store').peekAll('product')
};
});
}
});
Well, you probably could implement this in your adapter. This could give you some idea what you could do:
export default DS.JSONAPIAdapter.extend({
init() {
this._super(...arguments);
this.set('toLoad', {});
},
loadDebounces() {
const toLoad = this.get('toLoad');
this.set('toLoad', {});
const keys = Object.keys(toLoad);
const data = magicLoadForAllAllKeys(); // just do something you like here. Sent the keys as POST, or GET array, websockets, smoke signals..
Object.keys(data).forEach(key => {
toLoad[key].resolve(data[key]);
});
},
findAll (store, type, sinceToken, snapshotRecordArray) {
return new Ember.RSVP.Promise((resolve, reject) => {
this.set(`toLoad.${type}`, { resolve, reject });
Ember.run.debounce(this, this.loadDebounces, 1);
});
},
});
You basically can just debounce multiple requests and process them as one. However this is not RESTFull nor JSONAPI compliant. Just to mention this.

How to get page to update with new records from server without a route change?

I have an Ember app that uses server-side storage. In the products route, I have a list of products that I display in my product route (which are fetched in the usual way upon entering the route)
{{#each item in sortedProducts}}
{{/each}}
....
fetch
App.ProductRoute = Ember.Route.extend({
model: function(){
return Ember.RSVP.hash({
store: this.store.find('product'),
//other code ommitted
})
}
})
In the controller, I do the sorting
sortProperties: ['date:desc'] //dated added
sortedProducts: Ember.computed.sort('model', 'sortProperties'),
This works, however, I give the user the option to filter the records displayed. Upon clicking a button, an action is called that queries the server for a subset of records (it doesn't just filter the records that are already in the store cache)
actions: {
filterByPriceAndColor: function(){
this.store.find('product', {price: pricevariable, color: colorvariable});
}
}
This queries and returns the desired records, but the list on the page isn't updated i.e. the list on the page still displays all the records that are fetched upon application load.
Question: how do I get the page to update with the new records fetched from the server without a route change, (and will the solution integrate with the computed sort that already exists for ordering the entries by date)
To update your model from an action (or anywhere else) you simple need to set a new value for it and Ember will to the hard work for you.
In your case it should look like this:
actions: {
filterByPriceAndColor: function() {
var promise = this.store.find('product', {price: pricevariable, color: colorvariable});
var self = this;
promise.then(function(data) {
self.set('model', data);
});
}
}
Here is a JSBin demonstrating how it works: http://emberjs.jsbin.com/walunokaro/3/edit

How do I reload data and update a bound element after a user clicks a button?

Why is it that when I click 'Random', the information in the template isn't reset and the data isn't update?
I have data that I want to display after a REST endpoint is successfully reached. The REST data that's returned is a random database record, so I don't need to worry about randomizing my request or anything. I only need to reach the server via that URL. In this case, the URL is: localhost:8000/api/verses/0
My handlebars template looks like this:
app/templates/verses.hbs
<div id="panel">
<h3>{{model.reference_number}}
<h3>{{model.body}}</h3>
<button {{action "getAnotherVerse"}}>Random</button>
</div>
{{outlet}}
So, when the 'Random' button is clicked, the following should be invoked:
app/controllers/verses.js
import Ember from 'ember';
import DS from 'ember-data';
export default Ember.ObjectController.extend({
actions: {
getAnotherVerse: function() {
this.get('model').reload();
// This is where the text should be reset to the new data.
}
}
});
app/routers/verses.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.find('verse', '0');
}
});
When you fire getAnotherVerse you just take the current record(model) and simply reload it to fetch its latest data. I guess you want to call model method of your route once again, so model will be reset and you'll get brand new record from your server.
Move getAnotherVerse to your VersesRoute where you specify model for VersesController and try following code:
# app/routes/verses.js
model: function() {
return this.store.find('verse', '0');
},
actions: {
getAnotherVerse: function() {
this.refresh(); # beforeModel, model, afterModel, setupController will re-fire
}
}
If this still doesn't work, please try this:
# app/routes/verses.js
model: function() {
return this.store.fetch('verse', '0');
},
actions: {
getAnotherVerse: function() {
this.store.unloadAll('verse'); # I assume `verse` is your Model name
this.refresh(); # beforeModel, model, afterModel, setupController will re-fire
}
}
Your telling Ember Data to find the record with id = 0. Just guessing that your API endpoint is treating 0 as a special case and returning a record that does have an actual id.
Because Ember Data is using an identity map under the hood I'm guessing that when you call reload the data is creating a new record in the store. And therefore isn't triggering updates on the record that is being used for the model.
A better approach would be to just use
var that = this;
Ember.$.get('localhost:8000/api/verses/0')
.then(function(data) {
that.set('model', data);
});
You could push the data into the store too http://emberjs.com/guides/models/pushing-records-into-the-store/ and then it would be available if you need to find it by id later.
Another approach would be to create a custom adapter / serializer that could hide some of this, really depends on how your using ember data outside of this use case.

Ember Data is always fetching records for route

I just switched my application over to Ember CLI and Ember-Data (previously using Ember Model). When I transition to my employees route ember data does a GET request on the api's user route with a query as intended. However, whenever I leave this route and return it continues to perform a GET request on the api. Shouldn't these results be cached? I had a filter running on the model, but I removed it and still ran into the same issue.
Route w/ Filter:
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
// This queries the server every time I visit the route
return this.store.filter('user', {type: 'employee'}, function(user) {
if(! Ember.isEmpty(user.get('roles'))) {
return user.get('roles').contains('employee');
}
});
}
});
Route w/out Filter:
import Ember from 'ember';
// This still queries the server every time I visit the route
export default Ember.Route.extend({
model: function() {
return this.store.find('user');
}
});
Passing a second parameter into the filter function, {type: 'employee'}, turns it into a findQuery + filter, and find will always execute a query request. If you want to only call a particular resource once per SPA lifetime in a particular route you can add logic to keep track of it. The basic concept goes like this:
Check if you've fetched before
If you haven't fetch the records
Save the fetched records
return the saved fetched records
Example
export default Ember.Route.extend({
model: function() {
//resultPromise will return undefined the first time... cause it isn't defined
var resultPromise = this.get('resultPromise') || this.store.find('user');
this.set('resultPromise', resultPromise);
return resultPromise;
}
});
Additionally if you've already called find you can also just use store.all('type') to get all of the records for that type in the store client side without making a call to the server.

Computed property for the number of records in the store?

This may be abusing Ember, but I want to create a computed property for the number of items in the store.
I'm trying to prototype a UI that exists entirely client-side. I'm using fixture data with the local storage adapter. That way, I can start off with canned data, but I can also add data and have it persist across reloads.
As I'm currently working on the data layer, I've built a settings route that gives me a UI to reset various models. I would like to add a Handlebars expression like {{modelCount}} so I can see how many records there are in the store. That's quicker than using the Ember Data Chrome extension, which resets to the routes tab on every page reload.
The following will show me the number of records once, but does not change when the number of records changes:
modelCount: function() {
var self = this;
this.store.find("my_model").then(function(records) {
self.set("modelCount", records.get("length"));
});
}.property()
I get that the store is supposed to proxy an API in the real world, and find returns a promise, but that's about the limit of my knowledge. I don't know how tell Ember to that I want to know how many records there are, or if this is even a valid question.
Load the result of store.find into an Ember.ArrayController's content and then bind the length of content to modelCount. An example:
App.SomeRoute = Ember.Route.extend({
model: function(){
return this.store.find('my_model');
}
});
App.SomeController = Ember.ArrayController.extend({
modelCount: Ember.computed.alias('content.length')
});
See a working example in http://jsbin.com/iCuzIJE/1/edit.
I found a workable solution by combining the answer from #panagiotis, and a similar question, How to load multiple models sequentially in Ember JS route.
In my router, I sequentially load my models:
model: function() {
var self = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
self.store.find("model1").then(function(model1) {
self.store.find("model2").then(function(model2) {
self.store.find("model3").then(function(model3) {
resolve({
model1: model1,
model2: model2,
model3: model3
});
});
});
});
});
},
Then in my controller, I define simple computed properties:
model1Count: function() {
return this.get("model1.length");
}.property("model1.length"),
...