Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
Sayem Avatar asked Dec 29 '15 05:12

Sayem


1 Answers

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);
like image 71
David Furlong Avatar answered Oct 24 '22 20:10

David Furlong