Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Debugging the properties in an object which are in use
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('.')));
}
@sebinsua
Copy link
Author

sebinsua commented Aug 3, 2022

Note: this handles .then strangely because often code awaits on values. We should probably try to detect if this is a function and then treat it differently if so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment