I´m developing a Node.js & Express & Backbone & MongoDB app. i have a list of items fetched via url. In that list i want to put a select to sort items by price. I don´t know wich is the best way to do this sorting, maybe i have to put links in the select with a determinate url like [URL]&sort=1 and fetch it like i´m fetching all items, or maybe i could not use the link and fetch this collection from backbone in another and optimus way?
Thanks, regards
My view on this is as follows. Unless you must, avoid doing sorting on the server, but do it on the client. It is far more responsive that way. If you have 20 items, and want to sort by name (ascending or descending), quantity in inventory (ascending or descending), or price (same thing), far better to do it on the client.
When you must, is when you have 1,000 items. You simply will not load 1,000 items in a call and then sort them. You probably retrieve around 30-50 at a time, depending on the size of each item. So you need to have a way to tell the server, "give me the following 30 items" or, more accurately, "give me 30 items beginning at point X."
There are lots of ways to do it, even within REST. In general, you are best off passing the starting point and count via query parameters, as you did. So if you are getting widgets, and your API is
GET /widget
then you would have several query fields: field (which field you are sorting on), order (one of asc or des), count (an integer) and start (which point to start, either a record ID or an index).
That gives the following:
GET /widget?field=name&count=30&start=100&order=asc // get widgets sorted by field in ascending order, starting with the 100th widget and going for 30 widgets
GET /widget?field=price&count=20&start=225&order=desc // get widgets sorted by price from highest to lowest (descending order), starting with the 100th widget and going for 20 widgets
There are variants on this, e.g. instead of start and count you might do start and end. I have seen order called sort. But the idea is the same: those four fields give you all your server needs to know to retrieve a defined set of items.