k1r0s/kaop-ts

applyAspect not fully reading proto chain

k1r0s opened this issue · 1 comments

k1r0s commented

When decorating setState from React lib we get an error

k1r0s commented

posible solution

function applyAspect(definition) {
  const getPropertyDescriptor = (target, key) => {
    if(!target.prototype) new Error("property does not exist in the proto chain: " + key);
    const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
    if(!descriptor) return getPropertyDescriptor(Object.getPrototypeOf(target), key);
    else return descriptor;
  }
  return function (target) {
    const ctor = definition["constructor"] instanceof Array ? definition["constructor"] : []
    delete definition["constructor"]

    for (let key in definition) {
      definition[key].forEach(advice =>
        Object.defineProperty(target.prototype, key,
          advice(target, key, getPropertyDescriptor(target, key))))
    }

    ctor.forEach(advice => target = advice(target))
    return target
  }
}