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:
44
src/database/category.database.repository.ts
Normal file
44
src/database/category.database.repository.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user