bid-tool/auto-bid-server/src/modules/scraps/services/scrap-item-config.service.ts

71 lines
1.7 KiB
TypeScript

import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ScrapItem } from '../entities/scrap-item.entity';
import AppResponse from '@/response/app-response';
@Injectable()
export class ScrapItemsService {
constructor(
@InjectRepository(ScrapItem)
readonly scrapItemRepo: Repository<ScrapItem>,
) {}
async upsertScrapItems(items: ScrapItem[]) {
if (!items.length) return { inserted: 0, updated: 0 };
// Lấy keys để query bản ghi đã tồn tại
const keys = items.map((d) => ({
model: d.model,
scrap_config_id: d.scrap_config_id,
}));
// Tìm các bản ghi đã có trong DB
const existingItems = await this.scrapItemRepo.findBy(keys);
const toUpdate = [];
const toInsert = [];
items.forEach((itemData) => {
const exist = existingItems.find(
(e) =>
e.model === itemData.model &&
e.scrap_config_id === itemData.scrap_config_id,
);
if (exist) {
toUpdate.push({
...exist,
...itemData,
updated_at: new Date(),
});
} else {
toInsert.push(itemData);
}
});
// Thực hiện insert
if (toInsert.length) {
await this.scrapItemRepo.insert(toInsert);
}
// Thực hiện update
if (toUpdate.length) {
await this.scrapItemRepo.save(toUpdate);
}
return {
inserted: toInsert.length,
updated: toUpdate.length,
};
}
async upsertScrapItemsRes(items: ScrapItem[]) {
const rs = await this.upsertScrapItems(items);
if (!rs) throw new BadRequestException(AppResponse.toResponse(null));
return AppResponse.toResponse(rs);
}
}