Files
dinggadingga-backend/src/utils/sync.ts

31 lines
942 B
TypeScript

import { Logger } from '@nestjs/common';
import { rethrowIfRateLimited } from '../hiboutik/hiboutik.client';
/**
* Runs `action` on each item, one at a time: a failing item is logged and skipped, the others are still processed.
* A Hiboutik rate limit error stops the loop (rethrown): the next items would fail the same way.
* @param items
* @param action
* @param logger
* @param describe label of an item in the error log, e.g. "Hiboutik brand 12".
* @returns the number of failed items.
*/
export async function forEachSafely<T>(
items: T[],
action: (item: T) => Promise<unknown>,
logger: Logger,
describe: (item: T) => string,
): Promise<number> {
let nbFailed = 0;
for (const item of items) {
try {
await action(item);
} catch (error) {
rethrowIfRateLimited(error);
nbFailed++;
logger.error(`Failed to sync ${describe(item)}`, (error as Error)?.stack);
}
}
return nbFailed;
}