Skip to content

Commit

Permalink
Add pagination back using cursors
Browse files Browse the repository at this point in the history
  • Loading branch information
idevelop committed Mar 19, 2017
1 parent 46b1704 commit 716ea11
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
20 changes: 13 additions & 7 deletions cloud/functions/list-verses/index.js
@@ -1,13 +1,13 @@
var datastore = require('@google-cloud/datastore')();

exports.list = function(req, res) {
var page = req.param("page") || 1;
var cursor = req.param("cursor") || null;
fetchTotal(function(total, totalError) {
if (totalError) {
return res.status(500).send(totalError);
}

fetchVerses(page, function(verses, versesError) {
fetchVerses(cursor, function(versesError, verses, endCursor) {
if (versesError) {
return res.status(500).send(versesError);
}
Expand All @@ -21,7 +21,8 @@ exports.list = function(req, res) {
username: t.username,
text: t.text
}
})
}),
cursor: endCursor
};

res.status(200).set({
Expand All @@ -31,20 +32,25 @@ exports.list = function(req, res) {
});
};

function fetchVerses(page, callback) {
function fetchVerses(cursor, callback) {
var versesPerPage = 16;

var query = datastore.createQuery('Verse');
query.order('timestamp', {
descending: true
});

query.limit(versesPerPage);

datastore.runQuery(query, function(err, entities) {
if (cursor != null) {
query.start(cursor);
}

datastore.runQuery(query, function(err, entities, info) {
if (!err) {
callback(entities, null);
callback(null, entities, info.endCursor);
} else {
callback(null, err);
callback(err);
}
});
}
Expand Down
19 changes: 11 additions & 8 deletions web/scripts/ui.js
Expand Up @@ -63,30 +63,33 @@ var ui = {

init: function() {
ui.verses.template = $("#verseTemplate").html();
ui.verses.streamPosition = 0;
ui.verses.perPage = 16;

// http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
ui.isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;

$("#more > a").click(function(e) {
e.preventDefault();
ui.verses.streamPosition += ui.verses.perPage;
ui.verses.fetch();
ui.verses.fetch($("#more").attr("data-cursor"));
});

ui.verses.fetch();
},

fetch: function(start) {
fetch: function(cursor) {
$("#loading").show();
$.get(ui.verses.apiEndpoint, function(data) {
$("#more").hide();

var url = ui.verses.apiEndpoint;
if (cursor) {
url += "?cursor=" + cursor;
}

$.get(url, function(data) {
// TODO: check success
ui.verses.render(data.verses);
$("#total").html(ui.verses.formatTotal(data.total));
$("#loading").hide();

// $("#more").show();
$("#more").attr("data-cursor", encodeURIComponent(data.cursor)).show();
}, "json");
},

Expand Down

0 comments on commit 716ea11

Please sign in to comment.