thinky icon indicating copy to clipboard operation
thinky copied to clipboard

Possible to mixin schema?

Open 0xgeert opened this issue 9 years ago • 4 comments

I'm looking for something similar to mongoose plugins to add/mixin commonly used methods (define, defineStatic) and/or schema properties.

0xgeert avatar Mar 20 '15 15:03 0xgeert

Hum, that's currently not possible.

I've been asked for something similar before, so maybe it's something worth implementing.

neumino avatar Mar 21 '15 01:03 neumino

I hacked something similar before for one on my projects, modeled after ActiveSupport::Concern:

var createModel = thinky.createModel;
thinky.createModel = function(table, schema, concerns, options) {
  if (!Array.isArray(concerns) && typeof options == 'undefined') {
    options = concerns;
    concerns = undefined;
  }
  if (concerns) {
    _.defaults.apply(_, [schema].concat(_.invoke(concerns, 'schema', this)));
  }
  var model = createModel.call(this, table, schema, options);
  if (concerns) {
    _.invoke(concerns, 'included', this, model);
  }
  return model;
};

This lets me write, for example:

var Timestamps = {
  schema: function(thinky) {
    return {
      createdAt: thinky.type.date().default(thinky.r.now()),
      updatedAt: thinky.type.date().default(thinky.r.now())
    };
  },
  included: function(thinky, model) {
    model.docOn('saving', function(doc) {
      if (doc.isSaved()) {
        doc['updatedAt'] = new Date();
      }
    });
  }
};
var A = thinky.createModel('A', {id: thinky.type.string()}, [Timestamps]);

simonratner avatar Apr 25 '15 09:04 simonratner

:+1:

sandcastle avatar Jan 04 '16 06:01 sandcastle

:+1: This would be very useful.

cpg1111 avatar Jan 29 '16 22:01 cpg1111