mirror of
https://github.com/bitwarden/browser
synced 2025-12-19 01:33:33 +00:00
* Rename service-factory folder * Move cryptographic service factories * Move crypto models * Move crypto services * Move domain base class * Platform code owners * Move desktop log services * Move log files * Establish component library ownership * Move background listeners * Move background background * Move localization to Platform * Move browser alarms to Platform * Move browser state to Platform * Move CLI state to Platform * Move Desktop native concerns to Platform * Move flag and misc to Platform * Lint fixes * Move electron state to platform * Move web state to Platform * Move lib state to Platform * Fix broken tests * Rename interface to idiomatic TS * `npm run prettier` 🤖 * Resolve review feedback * Set platform as owners of web core and shared * Expand moved services * Fix test types --------- Co-authored-by: Hinton <hinton@users.noreply.github.com>
58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
/**
|
|
* Use as a Decorator on async functions, it will prevent multiple 'active' calls as the same time
|
|
*
|
|
* If a promise was returned from a previous call to this function, that hasn't yet resolved it will
|
|
* be returned, instead of calling the original function again
|
|
*
|
|
* Results are not cached, once the promise has returned, the next call will result in a fresh call
|
|
*
|
|
* Read more at https://github.com/bitwarden/jslib/pull/7
|
|
*/
|
|
export function sequentialize(cacheKey: (args: any[]) => string) {
|
|
return (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
|
|
const originalMethod: () => Promise<any> = descriptor.value;
|
|
const caches = new Map<any, Map<string, Promise<any>>>();
|
|
|
|
const getCache = (obj: any) => {
|
|
let cache = caches.get(obj);
|
|
if (cache != null) {
|
|
return cache;
|
|
}
|
|
cache = new Map<string, Promise<any>>();
|
|
caches.set(obj, cache);
|
|
return cache;
|
|
};
|
|
|
|
return {
|
|
value: function (...args: any[]) {
|
|
const cache = getCache(this);
|
|
const argsCacheKey = cacheKey(args);
|
|
let response = cache.get(argsCacheKey);
|
|
if (response != null) {
|
|
return response;
|
|
}
|
|
|
|
const onFinally = () => {
|
|
cache.delete(argsCacheKey);
|
|
if (cache.size === 0) {
|
|
caches.delete(this);
|
|
}
|
|
};
|
|
response = originalMethod
|
|
.apply(this, args)
|
|
.then((val: any) => {
|
|
onFinally();
|
|
return val;
|
|
})
|
|
.catch((err: any) => {
|
|
onFinally();
|
|
throw err;
|
|
});
|
|
|
|
cache.set(argsCacheKey, response);
|
|
return response;
|
|
},
|
|
};
|
|
};
|
|
}
|