feat(db): add database repositories
This commit is contained in:
36
src/database/customer.database.repository.ts
Normal file
36
src/database/customer.database.repository.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { Customer } from '../../prisma/generated/client';
|
||||
import { CustomerCreateInput } from '../../prisma/generated/models/Customer';
|
||||
|
||||
/** Database access to customers. Rows are matched with Hiboutik by `hiboutikId`. */
|
||||
@Injectable()
|
||||
export class CustomerDatabaseRepository {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getAll(): Promise<Customer[]> {
|
||||
return this.prisma.customer.findMany({
|
||||
orderBy: { hiboutikId: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates or updates the customer with the same `hiboutikId`. */
|
||||
async upsert(customer: CustomerCreateInput): Promise<Customer> {
|
||||
return this.prisma.customer.upsert({
|
||||
where: { hiboutikId: customer.hiboutikId },
|
||||
create: customer,
|
||||
update: customer,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the customers that no longer exist in Hiboutik.
|
||||
* Their addresses are deleted (onDelete: Cascade), their orders are kept with no customer (onDelete: SetNull).
|
||||
*/
|
||||
async deleteMissing(keptHiboutikIds: number[]): Promise<number> {
|
||||
const result = await this.prisma.customer.deleteMany({
|
||||
where: { hiboutikId: { notIn: keptHiboutikIds } },
|
||||
});
|
||||
return result.count;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user