Skip to content

Instantly share code, notes, and snippets.

@nickschot
Created January 8, 2017 14:28
Show Gist options
  • Save nickschot/71188eb58d5152943ac3c825e8ba0442 to your computer and use it in GitHub Desktop.
Save nickschot/71188eb58d5152943ac3c825e8ba0442 to your computer and use it in GitHub Desktop.
(Somewhat) Crude extension of the route included in ember-infinity to work correctly together with JSONAPI.
import Ember from 'ember';
import InfinityRoute from "ember-infinity/mixins/route";
export default Ember.Mixin.create(InfinityRoute, {
perPageParam : "page[size]",
pageParam : "page[number]",
totalPagesParam : "meta.total",//unused
/**
@method _nextPageLoaded
@param {Ember.Enumerable} newObjects The new objects to add to the model
@return {DS.RecordArray} returns the updated infinity model
@private
*/
_nextPageLoaded: function(newObjects) {
//Retrieve the last page number from the last page link
const totalPages = this.getLastPageNumber(newObjects.links.last);
this.set('_totalPages', totalPages);
let infinityModel = newObjects;
if (this.get('_firstPageLoaded')) {
if (typeof this.updateInfinityModel === 'function' &&
(this.updateInfinityModel !==
Ember.Object.extend(InfinityRoute).create().updateInfinityModel)) {
Ember.deprecate("EmberInfinity.updateInfinityModel is deprecated. "+
"Please use EmberInfinity.afterInfinityModel.",
false,
{id: 'ember-infinity.updateInfinityModel', until: '2.1'}
);
infinityModel = this.updateInfinityModel(newObjects);
} else {
infinityModel = this._doUpdate(newObjects);
}
}
this.set('_firstPageLoaded', true);
this._notifyInfinityModelUpdated(newObjects);
const canLoadMore = this.get('_canLoadMore');
infinityModel.set('reachedInfinity', !canLoadMore);
if (!canLoadMore) {
this._notifyInfinityModelLoaded();
}
return infinityModel;
},
getLastPageNumber: function(urlString) {
var queryString = urlString.slice(urlString.indexOf('?')+1);
return JSON.parse('{"' + decodeURI(queryString).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')["page[number]"];
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment