thinky icon indicating copy to clipboard operation
thinky copied to clipboard

Support for functions on sub-docs via proxies

Open davefinster opened this issue 8 years ago • 1 comments

On the back of my previous PR, I sought to investigate ways to avoid polluting the documents themselves with additional functions/properties, which has brought me to this branch of using javascript proxy objects instead. Hence, the only altered files are model.js (to add support for the proxy) and schema.js (to support extraction of functions from model definition).

There is one potentially breaking change that this introduces, which is that it causes issues with strict equality checks between an object passed to the document constructor and the document itself. This is because the constructor now returns the proxy object when sub-doc function support is required. I'm not sure how important this is in production use cases, but if the new functionality is not used then there is no breakage as the proxy step is skipped if it isn't needed.

Keen for any feedback. As I said in the other PR, this is functionally addressing the following use case:

var User = thinky.createModel("User", {
  id: String,
  contact: {
    email: String,
    someMethod: type.method().default(function(someParameter1, someParameter2) {
        // More complex logic than this...
        return this.email == someParameter1 || this.email == someParameter2;
    }
  }
});

Aside from defining virtual properties, there is (AFAIK) no way to define a method or function on a sub-document of a model?

Using my changes, the answer to the above would be:

var User = thinky.createModel("User", {
  id: String,
  contact: {
    email: String,
    someMethod: function(someParameter1, someParameter2) {
        // More complex logic than this...
        return this.email == someParameter1 || this.email == someParameter2;
    }
  }
});

Defining virtual properties on sub-objects is not currently feasible in all cases since not every function attached to an object produces a value or has output that belongs in a database.

davefinster avatar May 19 '16 01:05 davefinster

As a follow up, seems the automated integration fails due to the absence of Proxy, which indicates that it's running a fairly old node.js without ES6 support. All the tests pass on my local machine. Proxy support is present within Node.js since v0.7.8 but disabled by default behind the --harmony_proxies flag.

Perhaps this change would be better suited instead as a downstream repository of thinky unless the idea of a minimum node version is viable.

davefinster avatar May 19 '16 02:05 davefinster