adopted-ember-addons / validated-changeset

Buffering changes to form data
MIT License
36 stars 27 forks source link

getters/setters are executed against the original model, not the modified one #161

Open azhiv opened 2 years ago

azhiv commented 2 years ago

Consider the following class:

class A {
  foo = 1;

  get bar(): number {
    return 2 * this.foo;
  }

  set bar(value: number) {
    this.foo = value / 2;
  }
}

If you create a change buffer over an instance of this class and modify it:

changebuffer.set('foo', 2);
console.log(changebuffer.get('bar'));      // 2, but I'd expect 4

changebuffer.set('bar', 6);
console.log(changebuffer.get('foo'));      // 1, but I'd expect 3

the results are a bit unexpected. Would you consider getting the property descriptor

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(target), prop);

and then executing it against the change buffer instance?

snewcomer commented 2 years ago

This looks like a valid bug. Looking into it! Thx for submitting!

snewcomer commented 2 years ago

@azhiv you have presented us with quite an interesting problem! The reason is because you are getting the "not yet" applied value. The question is, if you haven't called changeset.execute(), what should we return for bar. Since bar derives its value from an internal value foo, if we got the descriptor, then we would get the original value since you have yet to call execute(). Do you happen to see a path forward here?

https://github.com/validated-changeset/validated-changeset/pull/165

Where we return the "change" instead of bar.

https://github.com/validated-changeset/validated-changeset/blob/b3f7f63ca2c0213ad6c81ee0084380ef0e8e6f6c/src/index.ts#L1045-L1047

azhiv commented 2 years ago

@snewcomer I don't see a way forward here unless you build/obtain an object that represents the current state of the amended entity. Using proxy is a way to go. We leverage it in our project for this purpose, so that inside the get function we possess both target (the original model) and receiver (the proxy object), so that it's possible to pass the latter to the descriptor call:

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(target), prop);
if (descriptor) {
  // method is either 'get' or 'set'
  const descriptorMethod = descriptor[method];
  if (!descriptor.enumerable && descriptorMethod) {
    // It is a corresponding method defined on the model. We invoke with this=Proxy
    // In this way it is evaluated with all changes applied to ChangeBuffer in place.
    return descriptorMethod.call(receiver, value),
...
snewcomer commented 2 years ago

@azhiv I don't see one either :(. If we execute the get, we may change state, which would be unintentional and against the paradigm of a changeset - to avoid mutations until you want them.