如何扩展bookshelf.js

时间:2016-03-09 18:05:14

标签: ecmascript-6 bookshelf.js

我有一个验证功能,我正在复制到几乎所有模型中。我想通过扩展基础bookshelf.Model对象来抽象它。我不确定在ES6中正确的解决方法是什么。我不想在没有书架的情况下这样做。

示例模型:

import bookshelf from '../bookshelf';
import Checkit from 'checkit';

const Design = bookshelf.Model.extend({
  tableName: 'foo',

  constructor: function() {
    bookshelf.Model.apply(this, arguments); // super()
    this.on('saving', this.validate.bind(this));
  },

  validations: {
    barColumn: ['required', 'integer', 'greaterThan:0'],
  },

  validate: function(model, attrs, options) {
    let validations;
    if (options.patch === true) {
      Object.keys(this.validations).forEach((value, index) => {
        if (this.attributes[index] !== undefined) {
          validations[index] = value;
        }
      });
    } else {
      validations = this.validations;
    }
    return new Checkit(validations).run(this.toJSON());
  }
});

export default Design;

main bookshelf file is here

2 个答案:

答案 0 :(得分:1)

我无法解决如何扩展Bookshelf,所以我解决了这个问题:

import bookshelf from '../bookshelf';
import validate from '../utils/validate';

const Design = bookshelf.Model.extend({
  tableName: 'foo',

  constructor: function() {
    bookshelf.Model.apply(this, arguments); // super()
    this.on('saving', validate);
  },

  validations: {
    barColumn: ['required', 'integer', 'greaterThan:0'],
  },
});

export default Design;

新的验证文件:

import Checkit from 'checkit';

export default function validate(model, attributes, options) {
  let validations;
  if (options.patch === true) {
    Object.keys(model.validations).forEach((value, index) => {
      if (attributes[index] !== undefined) {
        validations[index] = value;
      }
    });
  } else {
    validations = model.validations;
  }
  return new Checkit(validations).run(model.toJSON());
};

答案 1 :(得分:0)

我认为你需要Facade或Decorator模式+一些依赖注入。

我通过以下方式将Facade用于我自己的目的:

class MyFacade {

  constructor(legacyLibrary) {
    this.legacyLibrary = legacyLibrary;
  }

  newMethod() {
    this.legacyLibrary.doSomething();
    this.legacyLibrary.doSomethingElse();
  }

}

export default MyFacade;

装饰者的想法是一样的,但你应该扩展你现有的类。因此所有功能都将保持不变,但您将拥有更多方法。

装饰器的好处是你可以嵌套它们。用一个装饰,然后用另一个装饰等等。