Skip to content

Instantly share code, notes, and snippets.

@barelyknown
Created November 28, 2017 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barelyknown/06b12e83fe8af5b540289ea8c431547b to your computer and use it in GitHub Desktop.
Save barelyknown/06b12e83fe8af5b540289ea8c431547b to your computer and use it in GitHub Desktop.
Example mixin that queries for all records using Ember data, one page at a time.
import Mixin from '@ember/object/mixin';
import { inject } from '@ember/service';
import { get } from '@ember/object';
import { task } from 'ember-concurrency';
const PAGE_LIMIT = 10;
// Mixin anywhere you'd like to query for all records that match
// a filter, one page at a time. This can be helpful anywhere you need
// need all records loaded, but don't want to hit the server with long
// running requests.
// export default Route.create(QueryAllMixin, {
// model() {
// return this.get('queryAllTask').perform('membership', {
// filter: {
// user: this.get('sessionUser.userId'),
// },
// include: [
// 'organization',
// ].join(),
// page: {
// limit: 5,
// },
// });
// },
// });
export default Mixin.create({
store: inject(),
queryAllTask: task(function * (modelName, options = {}) {
options.page = {
offset: 0,
limit: get(options, 'page.limit') || PAGE_LIMIT,
};
return yield this.get('queryPageTask').perform(modelName, options, []);
}),
queryPageTask: task(function * (modelName, options, all) {
const page = yield this.get('store').query(modelName, options);
const records = page.toArray();
// To handle the case where the resource isn't paginated,
// we'll check to see if the records have previously been loaded
if (options.page.offset === 0) {
const isPagePreviouslyLoaded = records.every((record) => {
return all.includes(record);
});
if (isPagePreviouslyLoaded) {
return all;
}
}
all.pushObjects(records);
if (options.page.limit > records.length) {
return all;
} else {
options.page.offset += options.page.limit;
return this.get('queryPageTask').perform(modelName, options, all);
}
}),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment