Suppose you have a collection,
storage.threads
and each object has a property, text
, that you want to display. But it would be unreasonable to display every single thread at once, so some sort of pagination is in order. SQL has a handy LIMIT
command, and now AppJet has an equivalent, skip()
and limit()
.//Pagination variablesThe first step is to figure out where we're starting and how far to go, using request parameters found at the end of the URL. If not specified, we fall back to the front page (0) showing 10 items.
var start = parseInt(request.params.start) || 0
var items = parseInt(request.params.items) || 10
storage.threadsThen we make the database query and print the output in one shot. In order for this to work, each thread has to have been given a
.sortBy('-timestamp') //sort first so we skip the right ones
.skip(start)
.limit(items)
.forEach(function(thread){
printp(thread.text)
})
timestamp
property when it was created. The obvious thing to use is a Date object, which is really convenient because it easily casts itself to an integer when needed. So sortBy() sorts things from least to greatest, and since time always increases, it would sort in chronological order. All it takes to reverse this is prepending a minus sign to the argument. Now we simply skip anything before we want to start printing and limit the query to a certain number of items. It reads a lot like English. Finally, at the end we loop through the results of the query and print paragraph tags with the text inside.You can see a more advanced version of this example running live on http://post.appjet.net/, with the source code available. Next time I'll show you how to generate the links for pagination.