45 lines
1.6 KiB
TypeScript
45 lines
1.6 KiB
TypeScript
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;
|
|
}
|
|
}
|