Created
January 7, 2021 11:49
-
-
Save safareli/913e26b5a2a22f50762372271b75b107 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const consoleLogger = (...args: unknown[]) => { | |
console.log(...args); | |
}; | |
const consoleTracer = (...args: unknown[]) => { | |
console.trace(...args); | |
}; | |
type MonitorAction = "get" | "set"; | |
type MonitorDesc<T> = [prop: keyof T, ...actions: MonitorAction[]]; | |
const monitor = <T extends object>( | |
logger: (...args: unknown[]) => void, | |
...descriptions: MonitorDesc<T>[] | |
): ProxyHandler<T> => { | |
const shouldLog = (prop: PropertyKey, action: MonitorAction) => { | |
return descriptions.some( | |
([dProp, ...actions]) => dProp === prop && actions.indexOf(action) > -1 | |
); | |
}; | |
return { | |
get: (target, prop: keyof T) => { | |
if (shouldLog(prop, "get")) { | |
logger("GET: " + String(prop), target[prop], target); | |
} | |
return target[prop]; | |
}, | |
set: (target, prop: keyof T, val) => { | |
if (shouldLog(prop, "set")) { | |
logger("SET: " + String(prop), val, target[prop], target); | |
} | |
target[prop] = val; | |
return true; | |
}, | |
}; | |
}; | |
const x = new Proxy( | |
{ id: 7, data: "foo" }, | |
monitor(consoleLogger, ["id", "get"], ["data", "set", "get"]) | |
); | |
x.id; // GET: id 7 {id: 7, data: "foo"} | |
x.id = 10; | |
x.data; // GET: data foo {id: 10, data: "foo"} | |
x.data = "baz"; // SET: data baz foo {id: 10, data: "foo"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment