Files
shop-api/src/db/seeders/warrantySeeders.ts
T
morteza 78d8795155
Build and Deploy / build_and_deploy (push) Has been cancelled
update : bycryptjs
2026-06-14 08:49:13 +03:30

76 lines
2.4 KiB
TypeScript

import { cleanMongoData, extractDumpData, getCollectionData } from "./utils/extractDumpData";
import { StatusEnum } from "../../common/enums/status.enum";
import { Logger } from "../../core/logging/logger";
import { WarrantyModel } from "../../modules/warranty/models/warranty.model";
export const seedWarranty = async (logger: Logger) => {
try {
logger.info("Warranty seeding started");
// Extract data from dump
const dumpData = extractDumpData();
const warrantiesData = getCollectionData(dumpData, "warranties");
if (warrantiesData.length === 0) {
logger.warn("No warranty data found in dump, using fallback data");
await WarrantyModel.create({
name: "Iran Warranty Co.",
status: StatusEnum.Approved,
duration: "12 months",
logoUrl: "",
});
logger.info("Warranty seeding complete with fallback data!");
return;
}
// Clean and prepare warranty data
const cleanedWarranties = warrantiesData
.map((warranty) => {
const cleaned = cleanMongoData(warranty);
// Only include non-deleted warranties
if (cleaned.deleted) {
return null;
}
return {
name: cleaned.name,
status: cleaned.status || StatusEnum.Pending,
duration: cleaned.duration || "0",
logoUrl: cleaned.logoUrl || "",
};
})
.filter((w) => w !== null);
if (cleanedWarranties.length > 0) {
// Check for existing warranties and only create new ones to avoid duplicate key errors
let createdCount = 0;
let skippedCount = 0;
for (const warranty of cleanedWarranties) {
const existing = await WarrantyModel.findOne({ name: warranty.name });
if (!existing) {
try {
await WarrantyModel.create(warranty);
createdCount++;
} catch (error: any) {
// Handle duplicate key errors gracefully
if (error.code === 11000) {
logger.warn(`Skipping duplicate warranty: ${warranty.name}`);
skippedCount++;
} else {
throw error;
}
}
} else {
skippedCount++;
}
}
logger.info(`Warranty seeding complete! (${createdCount} created, ${skippedCount} skipped)`);
} else {
logger.warn("No valid warranties found after filtering");
}
} catch (error) {
logger.error("Error seeding warranties:", error);
}
};