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:
36
src/database/brand.database.repository.ts
Normal file
36
src/database/brand.database.repository.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Brand } from '../../prisma/generated/client';
|
||||
import { BrandCreateInput } from '../../prisma/generated/models/Brand';
|
||||
|
||||
/** Database access to brands. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||
@Injectable()
|
||||
export class BrandDatabaseRepository {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getAll(): Promise<Brand[]> {
|
||||
return this.prisma.brand.findMany({
|
||||
orderBy: { hiboutikId: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates or updates the brand with the same `hiboutikId`. */
|
||||
async upsert(brand: BrandCreateInput): Promise<Brand> {
|
||||
return this.prisma.brand.upsert({
|
||||
where: { hiboutikId: brand.hiboutikId },
|
||||
create: brand,
|
||||
update: brand,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the brands that no longer exist in Hiboutik.
|
||||
* Their products are kept: the relation is set to null (onDelete: SetNull).
|
||||
*/
|
||||
async deleteMissing(keptHiboutikIds: number[]): Promise<number> {
|
||||
const result = await this.prisma.brand.deleteMany({
|
||||
where: { hiboutikId: { notIn: keptHiboutikIds } },
|
||||
});
|
||||
return result.count;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user