Created
June 4, 2020 13:09
-
-
Save stephenh/e3ba7b9e37f6cac800fe61c89653e204 to your computer and use it in GitHub Desktop.
Blessed proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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