Created
December 29, 2023 13:36
-
-
Save karol-majewski/6f3f7d944de9c332b221093c0763bb37 to your computer and use it in GitHub Desktop.
Convert synchronous methods to async methods
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
type PromisifyMethods<T> = { | |
[K in keyof T]: T[K] extends AnyFunction ? (...parameters: Parameters<T[K]>) => Promise<ReturnType<T[K]>> : T[K]; | |
}; | |
type AsynchronousStorage = PromisifyMethods<Storage>; | |
export function promisify(storage: Storage): AsynchronousStorage { | |
return new Proxy(storage, { | |
get(target, name: string) { | |
if (typeof target[name] === 'function') { | |
return async function (...args: unknown[]) { | |
return Reflect.apply(target[name], storage, args); | |
}; | |
} | |
return Reflect.get(target, name, target); | |
}, | |
}) as unknown as AsynchronousStorage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment