From 7fdaea73c5c67565202e19d6182fc215427919c3 Mon Sep 17 00:00:00 2001 From: memdmp Date: Tue, 19 Aug 2025 20:40:19 +0000 Subject: feat: oidc attempt 1 --- src/lib/oncePromise.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/lib/oncePromise.ts (limited to 'src/lib/oncePromise.ts') diff --git a/src/lib/oncePromise.ts b/src/lib/oncePromise.ts new file mode 100644 index 0000000..f6ce775 --- /dev/null +++ b/src/lib/oncePromise.ts @@ -0,0 +1,30 @@ +const ensurePromise = (maybePromise: T | PromiseLike): Promise => + typeof maybePromise === 'object' && + maybePromise !== null && + 'then' in maybePromise && + typeof maybePromise.then === 'function' && + 'catch' in maybePromise && + typeof maybePromise.catch === 'function' && + 'finally' in maybePromise && + typeof maybePromise.finally === 'function' + ? (maybePromise as Promise) + : Promise.resolve(maybePromise); +/** Returns a function that caches successful promises until time runs out, and throws away unsuccessful ones */ +export const oncePromise = (create: () => Promise, timeout = -1) => { + let getPromise = (): Promise => { + const oldGetPromise = getPromise, + promise = ensurePromise(create()).catch((e) => { + getPromise = oldGetPromise; + throw e; + }), + expires = timeout > 0 ? performance.now() + timeout : 0; + return (getPromise = expires + ? ((() => + performance.now() > expires + ? oldGetPromise() + : promise) as () => Promise) + : () => promise)(); + }; + return () => getPromise(); +}; +export default oncePromise; -- cgit v1.2.3