1

I am write a compatibility layer over a legacy library function whose internal signature looks like —

function legacyLibraryFunction(context) {
  context.foo.bar = "data"
  return context
}

The new system however, doesn't recommend assigning custom properties directly to context and instead recommends using the context.set() method.

How do I pass context from the new system to the old one so that context.foo="data" ends up called context.set('foo', data) instead?

I'm guessing I can use Object.defineProperty for this, but I don't really understand how.

Shubham Kanodia
  • 6,036
  • 3
  • 32
  • 46

1 Answers1

0

Using a setter:

You can use a setter for this:

var wrappedContext = {
    set foo(val) {
        context.set('foo',val);
    }
}

Note: I'm assuming context.foo instead of context.foo.bar because the second part of your question does not quite match the example code.

This will create an object (wrappedContext) that will have a foo property that will call context.set() when you assign a value to it. So then you can do:

legacyLibraryFunction(wrappedContext);

Using a proxy:

Since you're using node 6.6 you can also use a proxy:

var wrappedContext = new Proxy(context,{
  set: function(obj, prop, value) {
    obj.set(prop,value);
  }
});
slebetman
  • 109,858
  • 19
  • 140
  • 171