Skip to content

Instantly share code, notes, and snippets.

@fl0w
Created May 6, 2018 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fl0w/37c8a9a2b824a33bbb2cdb7abe845506 to your computer and use it in GitHub Desktop.
Save fl0w/37c8a9a2b824a33bbb2cdb7abe845506 to your computer and use it in GitHub Desktop.
The correct way to define custom bookshelf Collections with registry plugin
const bookshelf = require('bookshelf')
class Users extends bookshelf.Collection {
get model () {
return User
}
}
class User extends bookshelf.Model {
static collection (...args) {
return new Users(...args)
}
}
bookshelf.collection('Users', Users)
bookshelf.model('User', User)
@fl0w
Copy link
Author

fl0w commented May 6, 2018

const account = await bookshelf.model('Account').forge({ id: 1 }).fetch({ withRelated: 'users' })
account.related('users') instanceof Users // -> true
account.users() instanceof Users // -> true
bookshelf.model('User').collection() instanceof Users // -> true

This'll also allow to define custom logic when collection is eager loaded:

class Users extends bookshelf.Collection {
  initialize (...args) {
    super.initialize(...args)
    this.on('fetching', (collection, attrs, options) => {
      if (options.isEager) {
        // Collection is eager loaded, do something amazing
      }
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment