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/product.database.repository.ts
Normal file
44
src/database/product.database.repository.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Product } from '../../prisma/generated/client';
|
||||
import { ProductCreateInput } from '../../prisma/generated/models/Product';
|
||||
|
||||
/** Database access to products. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||
@Injectable()
|
||||
export class ProductDatabaseRepository {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getAll(): Promise<Product[]> {
|
||||
return this.prisma.product.findMany({
|
||||
orderBy: { hiboutikId: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates or updates the product with the same `hiboutikId`. On update, the relations missing from the input are unlinked. */
|
||||
async upsert(product: ProductCreateInput): Promise<Product> {
|
||||
return this.prisma.product.upsert({
|
||||
where: { hiboutikId: product.hiboutikId },
|
||||
create: product,
|
||||
update: {
|
||||
...product,
|
||||
// an undefined relation is ignored by Prisma on update: explicitly unlink relations removed in Hiboutik
|
||||
brand: product.brand ?? { disconnect: true },
|
||||
category: product.category ?? { disconnect: true },
|
||||
supplier: product.supplier ?? { disconnect: true },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes products (and their versions, by cascade).
|
||||
* Order lines keep their own snapshot of the product, their link is set to null.
|
||||
*/
|
||||
async deleteAll(productIds: string[]): Promise<number> {
|
||||
if (productIds.length === 0) return 0;
|
||||
|
||||
const result = await this.prisma.product.deleteMany({
|
||||
where: { id: { in: productIds } },
|
||||
});
|
||||
return result.count;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user