Files
dinggadingga-backend/src/database/category.database.repository.ts
MastersGame 27d0e0149d feat(db): add database repositories
Upserts keyed on hiboutikId and deletion of the rows that no longer exist in Hiboutik.
2026-11-05 23:00:48 +01:00

45 lines
1.6 KiB
TypeScript

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;
}
}