treojs / treo

Consistent API to IndexedDB
http://treojs.com
MIT License
258 stars 18 forks source link

Support for descending order on cursor #28

Open lpschz opened 9 years ago

lpschz commented 9 years ago

If I got time will try to do it my own in a PR for treo, but would be nice to support descending order using opts.direction:

Store.prototype.cursor = function(opts, cb) {
  var name = this.name;
  this.db.transaction('readonly', [name], function(err, tr) {
    if (err) return cb(err);
    var store = opts.index
      ? tr.objectStore(name).index(opts.index)
      : tr.objectStore(name);
    var req = store.openCursor(parseRange(opts.range), opts.direction);
alekseykulikov commented 9 years ago

Hi, it would be a nice addition. I think we can switch cursor API to something more expressive like:

store.cursor([range], [direction], iterator);
store.cursor({ gte: 'some-key' }, iterator); // filter by key (95% use cases)
store.cursor(iterator); // for each
store.cursor('prev', iterator); // reverse cursor
index.cursor('prevunique', iterator); // reverse cursor by unique values

Not sure, that difference between prevunique and prev has any sense without reading docs, but we definitely have to have it.

lpschz commented 9 years ago

Not sure what's the preferred approach, but I personally prefer passing one object instead of having params, specially for when you forget the order of the params, its clearer... opinions anyone? @unkillbob ?

store.cursor({
    iterator: function() {},
    range: ..,
    direction: ...
});

rather than

store.cursor(IDBKeyRange(), 'prev', function() {

});
alekseykulikov commented 9 years ago

@capsula4 Yes, I prefer your approach as well. But this case, seems like an exception. You always pass an iterator, also most of the time you pass range. So in 99% cases, it's:

cursor(iterator) // or
cursor(range, iterator)

But if you really want to go advanced, you pass direction, in order that similar to original .openCursor(). For me it looks convinient.

I introduced opts in the beginning, because I thought, there're could be many options, but now I see, that it's only 3.

alekseykulikov commented 9 years ago

@capsula4 after a few tries to implement cursor([range], [direction], iterator) semantic, I realize, that cursor(opts) much easier for validation and implementation. And this is low level, so let's keep it as is, and "direction" support is implemented and will be shipped in #29 :)

lpschz commented 9 years ago

Cool sounds good to me! Awesome work Aleksey!