feat(db): add database repositories

Upserts keyed on hiboutikId and deletion of the rows that no longer exist in Hiboutik.
This commit is contained in:
MastersGame
2026-11-05 23:00:48 +01:00
parent db699822f9
commit 27d0e0149d
6 changed files with 232 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { Category } from '../../prisma/generated/client';
import { CategoryCreateInput } from '../../prisma/generated/models/Category';
/** Database access to categories. Rows are matched with Hiboutik by `hiboutikId`. */
@Injectable()
export class CategoryDatabaseRepository {
constructor(private readonly prisma: PrismaService) {}
async getAll(): Promise<Category[]> {
return this.prisma.category.findMany({
orderBy: { hiboutikId: 'asc' },
});
}
/** Creates or updates the category with the same `hiboutikId`. */
async upsert(category: CategoryCreateInput): Promise<Category> {
return this.prisma.category.upsert({
where: { hiboutikId: category.hiboutikId },
create: category,
update: category,
});
}
/** Links a category to its parent (null for a root category). Both must already exist. */
async setParent(hiboutikId: number, parentHiboutikId: number | null): Promise<Category> {
return this.prisma.category.update({
where: { hiboutikId },
data: { parent: parentHiboutikId ? { connect: { hiboutikId: parentHiboutikId } } : { disconnect: true } },
});
}
/**
* Deletes the categories that no longer exist in Hiboutik.
* Their products and sub-categories are kept: the relation is set to null (onDelete: SetNull).
*/
async deleteMissing(keptHiboutikIds: number[]): Promise<number> {
const result = await this.prisma.category.deleteMany({
where: { hiboutikId: { notIn: keptHiboutikIds } },
});
return result.count;
}
}