Skip to content

Instantly share code, notes, and snippets.

@stephenh
Created June 4, 2020 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenh/e3ba7b9e37f6cac800fe61c89653e204 to your computer and use it in GitHub Desktop.
Save stephenh/e3ba7b9e37f6cac800fe61c89653e204 to your computer and use it in GitHub Desktop.
Blessed proxy
class Target {
ref = new Ref();
foo() {
return this.bar();
}
bar() {
return this.ref;
}
}
class Ref {
zaz() {
return (this as any).__secret;
}
}
function newBlessedHandler(secret: string, seenProps: string[]): ProxyHandler<any> {
const handler: ProxyHandler<any> = {
get(target, prop) {
seenProps.push(String(prop));
if (prop === "__secret") {
return secret;
}
const next = Reflect.get(target, prop);
return typeof next === "object" && next ? new Proxy(next, handler) : next;
},
};
return handler;
}
describe("foo", () => {
it("foo", () => {
const target = new Target();
const seenProps: string[] = [];
const handler = newBlessedHandler("secret", seenProps);
target.foo();
expect(seenProps).toEqual([]);
const proxy = new Proxy(target, handler);
const foundSecret = proxy.foo().zaz();
expect(seenProps).toEqual(["foo", "bar", "ref", "zaz", "__secret"]);
expect(foundSecret).toEqual("secret");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment