Files
dinggadingga-backend/src/services/hiboutik/brand.hiboutik.service.ts
MastersGame 30c56f9330 feat(sync): trust Hiboutik answers for deletions
A successful (2xx) answer from Hiboutik is now the truth, even an empty
list: records missing from it are deleted. The "empty list means API
issue" safety nets are removed.

Deletion stays safe because a failed call deletes nothing: HTTP errors
throw, and the new HiboutikClient.getList (used by getAllPages and the
non-paginated lists) also throws on a 2xx body that is not a list, so a
malformed answer is never mistaken for an empty list. A 2xx without body
is an empty list.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 10:11:34 +01:00

35 lines
1.6 KiB
TypeScript

import { Injectable, Logger } from '@nestjs/common';
import { BrandHiboutikRepository } from '../../hiboutik/brand.hiboutik.repository';
import { BrandDatabaseRepository } from '../../database/brand.database.repository';
import { BrandConverter } from '../../models/converter/brand.converter';
import { forEachSafely } from '../../utils/sync';
@Injectable()
export class BrandHiboutikService {
private readonly logger = new Logger('BrandHiboutikService');
constructor(
private readonly brandHiboutikRepository: BrandHiboutikRepository,
private readonly brandDatabaseRepository: BrandDatabaseRepository,
private readonly brandConverter: BrandConverter,
) {}
/** Mirrors Hiboutik brands: upserts each of them, then deletes the brands missing from Hiboutik. */
async syncBrands() {
const hiboutikBrands = await this.brandHiboutikRepository.getBrands();
// One upsert per brand: an invalid brand must not prevent the others from being saved
const nbFailed = await forEachSafely(
this.brandConverter.fromHiboutikList(hiboutikBrands),
(brand) => this.brandDatabaseRepository.upsert(brand),
this.logger,
(brand) => `Hiboutik brand ${brand.hiboutikId}`,
);
// Hiboutik is trusted: a successful (2xx) answer, even an empty list, is the truth. An HTTP error throws before this point.
const nbDeleted = await this.brandDatabaseRepository.deleteMissing(hiboutikBrands.map((dto) => Number(dto.brand_id)));
this.logger.log(
`Brands sync ended: ${hiboutikBrands.length - nbFailed}/${hiboutikBrands.length} synced, ${nbFailed} failed, ${nbDeleted} deleted.`,
);
}
}