feat: emit errors as part of fetchFromMultipleSources
This commit is contained in:
@@ -8,29 +8,43 @@ type OptionalArgs<T> =
|
||||
fetchFromCache?: undefined;
|
||||
};
|
||||
|
||||
interface FetchFromMultipleSourcesResult<T> {
|
||||
result: T | null;
|
||||
errors: (Error | string | undefined)[] | null;
|
||||
}
|
||||
|
||||
export async function fetchFromMultipleSources<T>(
|
||||
fetchPromises: (() => Promise<T | null | undefined>)[],
|
||||
args?: OptionalArgs<T>,
|
||||
) {
|
||||
): Promise<FetchFromMultipleSourcesResult<T>> {
|
||||
let result = await args?.fetchFromCache?.();
|
||||
if (result) {
|
||||
return result;
|
||||
return { result, errors: null };
|
||||
}
|
||||
|
||||
if (fetchPromises.length === 0) {
|
||||
throw new Error("fetchPromises cannot be empty");
|
||||
}
|
||||
|
||||
for (const promise of fetchPromises) {
|
||||
let errors: Record<number, Error> = {};
|
||||
for (let i = 0; i < fetchPromises.length; i++) {
|
||||
const promise = fetchPromises[i];
|
||||
try {
|
||||
result = await promise();
|
||||
if (result) break;
|
||||
} catch (e) {}
|
||||
} catch (e) {
|
||||
errors[i] = e as Error;
|
||||
}
|
||||
}
|
||||
|
||||
if (args?.saveInCache && result) {
|
||||
await args.saveInCache(result);
|
||||
}
|
||||
|
||||
return result ?? null;
|
||||
result = result ?? null;
|
||||
return {
|
||||
result,
|
||||
errors:
|
||||
!result && Object.keys(errors).length > 0 ? Object.values(errors) : null,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user