Files
dinggadingga-backend/src/database/productVersion.database.repository.ts

45 lines
1.7 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { Prisma, ProductVersion } from '../../prisma/generated/client';
import { ProductVersionCreateInput } from '../../prisma/generated/models/ProductVersion';
/** Database access to product versions (one per Hiboutik size), identified by their product and `hiboutikSizeId`. */
@Injectable()
export class ProductVersionDatabaseRepository {
constructor(private readonly prisma: PrismaService) {}
async getAll(): Promise<ProductVersion[]> {
return this.prisma.productVersion.findMany({
orderBy: { hiboutikSizeId: 'asc' },
});
}
/**
* Creates or updates the version of `productId` with the same `hiboutikSizeId`.
* @param db transaction client, to run it inside a transaction.
*/
async upsert(
productId: string,
productVersion: ProductVersionCreateInput,
db: Prisma.TransactionClient = this.prisma,
): Promise<ProductVersion> {
return db.productVersion.upsert({
where: { productId_hiboutikSizeId: { productId: productId, hiboutikSizeId: productVersion.hiboutikSizeId } },
create: productVersion,
update: productVersion,
});
}
/**
* Deletes the versions of a product that no longer exist in Hiboutik.
* Order lines keep their own snapshot of the product, their link is set to null.
* @param db transaction client, to run it inside a transaction.
*/
async deleteMissing(productId: string, keptHiboutikSizeIds: number[], db: Prisma.TransactionClient = this.prisma): Promise<number> {
const result = await db.productVersion.deleteMany({
where: { productId, hiboutikSizeId: { notIn: keptHiboutikSizeIds } },
});
return result.count;
}
}