jtwebman / bookshelf-scopes

Giving you Rails like scopes in Bookshelf.js.
MIT License
14 stars 3 forks source link

es6 class support #1

Closed lancecarlson closed 6 years ago

lancecarlson commented 7 years ago

Migrating this from the old repo. I tried testing this with 1.5.0 and I'm still having issues. Any confirmation of this?

I'm probably doing something wrong and completely overlooking something obvious, but I'm trying to get this working with es6 style classes (which work with bookshelf)

Example:


class User extends model.Model {
  get scopes() {
    return {
      active: (qb) => {
    return qb.where({active: true})
      }
    }
  }
}

User.active is not a function. Ideally this would also be accessible from qb/collections too somehow. When I do User.query(qb => qb.active()) should also be defined.
lancecarlson commented 7 years ago

What's weird, is that I think defining a default scope works

jtwebman commented 7 years ago

Sorry for the delay. I'll take a look today.

jordaaash commented 7 years ago

Easy solution I found! Call bookshelf.Model.extended on your class, like this:

// your base model class
class Model extends bookshelf.Model {
    // added this to allow chaining for export convenience, see below
    static extended (Child) {
        super.extended(Child);
        return Child;
    }

    // Model.protototype.scopes; these will be inherited by subclasses
    get scopes () {
        // nondestructive assignment allows inheritance of generic scopes
        return Object.assign({}, super.scopes, {
            latest (query) {
                query.orderBy('created_at', 'DESC').limit(1);
            }
        };
    }

    // empty setter is required for the plugin to write to
    set scopes (scopes) {
    }
}

class Something extends Model {
    // Something.prototype.scopes; this is what the plugin reads from
    get scopes () {
        // nondestructive assignment allows scope inheritance
        return Object.assign({}, super.scopes, {
            // Something's scopes
        };
    }

    // empty setter is required for the plugin to write to
    set scopes (scopes) {
    }
}

// call extended and export; the plugin will properly set up static and prototype methods
module.exports = Model.extended(Something);
jtwebman commented 6 years ago

Looks like there might be a solution for this. If not I am open to a PR if one is found. For now I am going to close the ticket.