feat: create function to handle fetching data from multiple sources
This helps since sometimes the data sources have issues occasionally
This commit is contained in:
36
src/libs/fetchFromMultipleSources.ts
Normal file
36
src/libs/fetchFromMultipleSources.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
type OptionalArgs<T> =
|
||||
| {
|
||||
saveInCache: (result: NonNullable<T>) => Promise<void>;
|
||||
fetchFromCache: () => Promise<T | null | undefined>;
|
||||
}
|
||||
| {
|
||||
saveInCache?: undefined;
|
||||
fetchFromCache?: undefined;
|
||||
};
|
||||
|
||||
export async function fetchFromMultipleSources<T>(
|
||||
fetchPromises: (() => Promise<T | null | undefined>)[],
|
||||
args?: OptionalArgs<T>,
|
||||
) {
|
||||
let result = await args?.fetchFromCache?.();
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (fetchPromises.length === 0) {
|
||||
throw new Error("fetchPromises cannot be empty");
|
||||
}
|
||||
|
||||
for (const promise of fetchPromises) {
|
||||
try {
|
||||
result = await promise();
|
||||
if (result) break;
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
if (args?.saveInCache && result) {
|
||||
await args.saveInCache(result);
|
||||
}
|
||||
|
||||
return result ?? null;
|
||||
}
|
||||
Reference in New Issue
Block a user