2022-08-16 23:59:11 +00:00
|
|
|
// Copyright 2022 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2023-08-10 16:43:33 +00:00
|
|
|
import { v4 as generateUuid } from 'uuid';
|
|
|
|
|
2022-08-16 23:59:11 +00:00
|
|
|
import type { ExplodePromiseResultType } from '../util/explodePromise';
|
2023-08-10 16:43:33 +00:00
|
|
|
|
|
|
|
export type SingleServePromiseIdString = string & { __single_serve: never };
|
2022-08-16 23:59:11 +00:00
|
|
|
|
|
|
|
// This module provides single serve promises in a pub/sub manner.
|
|
|
|
// One example usage is if you're calling a redux action creator but need to
|
|
|
|
// await some result within it, you may pass in this promise and access it in
|
|
|
|
// other parts of the app via its referencing UUID.
|
|
|
|
|
2023-08-10 16:43:33 +00:00
|
|
|
const promises = new Map<
|
|
|
|
SingleServePromiseIdString,
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
ExplodePromiseResultType<any>
|
|
|
|
>();
|
2022-08-16 23:59:11 +00:00
|
|
|
|
|
|
|
export function set<T>(
|
|
|
|
explodedPromise: ExplodePromiseResultType<T>
|
2023-08-10 16:43:33 +00:00
|
|
|
): SingleServePromiseIdString {
|
|
|
|
let uuid = generateUuid() as SingleServePromiseIdString;
|
2022-08-16 23:59:11 +00:00
|
|
|
|
|
|
|
while (promises.has(uuid)) {
|
2023-08-10 16:43:33 +00:00
|
|
|
uuid = generateUuid() as SingleServePromiseIdString;
|
2022-08-16 23:59:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
promises.set(uuid, {
|
|
|
|
promise: explodedPromise.promise,
|
|
|
|
resolve: value => {
|
|
|
|
promises.delete(uuid);
|
|
|
|
explodedPromise.resolve(value);
|
|
|
|
},
|
|
|
|
reject: err => {
|
|
|
|
promises.delete(uuid);
|
|
|
|
explodedPromise.reject(err);
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
return uuid;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function get<T>(
|
2023-08-10 16:43:33 +00:00
|
|
|
uuid: SingleServePromiseIdString
|
2022-08-16 23:59:11 +00:00
|
|
|
): ExplodePromiseResultType<T> | undefined {
|
|
|
|
return promises.get(uuid);
|
|
|
|
}
|