Created
June 29, 2022 10:24
-
-
Save sebinsua/724fa9d4390bd2c738da13389e0508ed to your computer and use it in GitHub Desktop.
Debugging the properties in an object which are in use
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
import DeepProxy from 'proxy-deep'; | |
export function withDeepPropertyAccessEmitter<T extends object>( | |
object: T, | |
emit: (info: { | |
path: (string | symbol)[]; | |
target: T; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
value: any; | |
}) => void | |
): T { | |
return new DeepProxy(object, { | |
get(target, handler, receiver) { | |
const propertyKey = handler.valueOf(); | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | |
const value = Reflect.get(target, propertyKey, receiver); | |
if (typeof value === 'object' && value !== null) { | |
return this.nest(value); | |
} | |
if (typeof value === 'function') { | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | |
return value; | |
} | |
if (propertyKey === 'then') { | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | |
return value; | |
} | |
if (propertyKey === 'length' && Array.isArray(target)) { | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | |
return value; | |
} | |
const fullPath = [...this.path, propertyKey].map((p) => | |
typeof p === 'number' || (typeof p === 'string' && /^\d+$/.test(p)) ? '<number>' : p | |
); | |
emit({ | |
path: fullPath, | |
target, | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | |
value, | |
}); | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | |
return value; | |
}, | |
}); | |
} | |
export function withDeepPropertyAccessLogger<T extends object>(objectName: string, object: T, intervalMs = 5_000): T { | |
const paths = new Set<string>(); | |
setInterval(() => { | |
if (paths.size > 0) { | |
console.table(Array.from(paths).map((path) => ({ [`${objectName} (read access)`]: path }))); | |
} | |
paths.clear(); | |
}, intervalMs); | |
return withDeepPropertyAccessEmitter(object, ({ path }) => paths.add([objectName, ...path].join('.'))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: this handles
.then
strangely because often codeawait
s on values. We should probably try to detect if this is afunction
and then treat it differently if so.