简体   繁体   中英

Writing bookshelf models in es6

Is there any way to write a bookshelf model using es6 classes? I can see the bookshelf source itself has been written in es6. But all the examples and sources that I have come across are written in es5. I saw an elaborate github issue on this that states that it's possible but it mostly discusses few errors regarding writing the models in classes. How do I write and use a bookshelf model with es6 classes?

Yes you can!

// database.js
import config from '../../knexfile';
import knex from 'knex';
import bookshelf from 'bookshelf';

const Bookshelf = bookshelf(knex(config[process.env.NODE_ENV || 'development']));

Bookshelf.plugin('registry'); // Resolve circular dependencies with relations
Bookshelf.plugin('visibility');

export default Bookshelf;


// Administers.js
import Bookshelf from '../database'
import { createValidatorPromise as createValidator, required, email as isEmail } from '../../utils/validation';
import { User, Organization } from '../';
import { BasicAdministersView, DetailedAdministersView } from '../../views/index';

class Administers extends Bookshelf.Model {

  get tableName() { return 'administers'; }

  get hasTimestamps() { return true; }

  view(name){
    return new ({
      basic: BasicAdministersView,
      detailed: DetailedAdministersView
    }[name])(this);
  }

  user() {
    console.log(User);
    return this.belongsTo('User', 'user_id');
  }

  organization() {
    return this.belongsTo('Organization', 'organization_id');
  }
}

export default Bookshelf.model('Administers', Administers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM