All files / server/utils bookshelf-returning.js

100% Statements 20/20
75% Branches 6/8
100% Functions 5/5
100% Lines 19/19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 441x   1x   1x       181x     181x 89x 83x 83x 83x 83x           6x         181x 89x 83x   6x 6x 6x 6x 6x                
module.exports = bookshelf => {
 
  const proto = bookshelf.Model.prototype;
 
  bookshelf.Model = bookshelf.Model.extend({
    returningProperties: '*',
 
    constructor: function() {
      proto.constructor.apply(this, arguments);
 
      // Workaround (see https://github.com/tgriesser/bookshelf/issues/507#issuecomment-99634467)
      this.on('saving', (model, attrs, options) => {
        if (options.method === 'insert') {
          const returningProperties = this.returningProperties;
          Object.defineProperty(options.query._single, 'returning', {
            get() { return returningProperties; },
            set() { return returningProperties; },
            configurable: true,
            enumerable: true,
            writeable: true,
          });
        } else {
          options.query.returning.call(options.query, this.returningProperties);
        }
      });
 
      // Workaround (see https://github.com/tgriesser/bookshelf/issues/507#issuecomment-99634467)
      this.on('saved', (model, attrs, options) => {
        if (options.method === 'insert') {
          model.set(model.parse(model.id));
        } else {
          const id = model.get(model.idAttribute);
          Eif (id) {
            const attr = attrs.find(attr => attr.id === id);
            Eif (attr) {
              model.set(model.parse(attr));
            }
          }
        }
      });
    }
  });
};