2008-07-30

AppJet databases now faster and more powerful.

Good morning, everyone. You might like to know that AppJet, the cloud-based JavaScript framework that nobody knows about, just released an update, making it more efficient for the CPU and easier on the coder, a win-win. There are new methods that make it easy to filter and paginate and data sets. See the AppJet change log for specifics.I have prepared an example to show the new features in action.

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 variables
var start = parseInt(request.params.start) || 0
var items = parseInt(request.params.items) || 10
The 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.
storage.threads
.sortBy('-timestamp') //sort first so we skip the right ones
.skip(start)
.limit(items)
.forEach(function(thread){
printp(thread.text)
})
Then 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 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.

No comments: