neumino / thinky

JavaScript ORM for RethinkDB
http://justonepixel.com/thinky/
Other
1.12k stars 128 forks source link

Possible to mixin schema? #201

Open 0xgeert opened 9 years ago

0xgeert commented 9 years ago

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

neumino commented 9 years ago

Hum, that's currently not possible.

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

simonratner commented 9 years ago

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]);
sandcastle commented 8 years ago

:+1:

cpg1111 commented 8 years ago

:+1: This would be very useful.