feat: add public method utilities and corresponding tests

This commit is contained in:
tone
2025-11-15 18:07:21 +08:00
parent 36e0c17ad7
commit ab289186f1
4 changed files with 70 additions and 3 deletions

View File

@@ -4,8 +4,12 @@ export const makeId = () => md5(`${Date.now()}${Math.random()}`);
export const isObject = (v: unknown): v is Record<string, any> => typeof v === 'object' && v !== null;
export const isArray = (v: unknown): v is Array<unknown> => Array.isArray(v);
export const isString = (v: unknown): v is string => typeof v === 'string';
export const isFunction = (v: unknown): v is Function => typeof v === 'function';
export type ObjectType = Record<string, any>;
export type ToDeepPromise<T> = {
@@ -41,4 +45,40 @@ export async function getRandomAvailablePort() {
server.listen(0);
})
}
const publicMethodMap = new WeakMap<Function, boolean>();
export function publicMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
publicMethodMap.set(descriptor.value, true);
};
export function isPublicMethod(target: Function) {
return publicMethodMap.get(target);
};
export function markAsPublicMethod<T extends Function | Record<any, unknown> | unknown>(obj: T, options?: {
deep?: boolean
}): T {
const accessed = new Set();
function markAs(obj: Function | Record<any, unknown> | unknown) {
if (accessed.has(obj)) {
return;
}
if (isFunction(obj)) {
publicMethodMap.set(obj, true);
} else if (isObject(obj)) {
accessed.add(obj);
Object.values(obj).forEach(subObj => {
if (isFunction(subObj)) {
publicMethodMap.set(subObj, true);
}
if (options?.deep && isObject(subObj)) {
markAs(subObj);
}
});
}
}
markAs(obj);
return obj;
}