69 lines
1.8 KiB
TypeScript
69 lines
1.8 KiB
TypeScript
|
|
import { NextResponse } from "next/server";
|
||
|
|
import { PrismaClient } from "@prisma/client";
|
||
|
|
import fs from "fs/promises";
|
||
|
|
import path from "path";
|
||
|
|
import { parse } from "csv-parse/sync";
|
||
|
|
|
||
|
|
// CSV location
|
||
|
|
const csvFilePath = path.resolve(process.cwd(), "public/artefacts.csv");
|
||
|
|
const prisma = new PrismaClient();
|
||
|
|
|
||
|
|
type CsvRow = {
|
||
|
|
Type: string;
|
||
|
|
WarehouseArea: string;
|
||
|
|
EarthquakeId: string;
|
||
|
|
Required?: string;
|
||
|
|
ShopPrice?: string;
|
||
|
|
PickedUp?: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
function stringToBool(val: string | undefined, defaultValue: boolean = false): boolean {
|
||
|
|
if (!val) return defaultValue;
|
||
|
|
return /^true$/i.test(val.trim());
|
||
|
|
}
|
||
|
|
|
||
|
|
export async function POST() {
|
||
|
|
try {
|
||
|
|
// 1. Read file
|
||
|
|
const fileContent = await fs.readFile(csvFilePath, "utf8");
|
||
|
|
|
||
|
|
// 2. Parse CSV
|
||
|
|
const records: CsvRow[] = parse(fileContent, {
|
||
|
|
columns: true,
|
||
|
|
skip_empty_lines: true,
|
||
|
|
});
|
||
|
|
|
||
|
|
// 3. Map records to artefact input
|
||
|
|
const artefacts = records.map((row) => ({
|
||
|
|
type: row.Type,
|
||
|
|
warehouseArea: row.WarehouseArea,
|
||
|
|
earthquakeId: parseInt(row.EarthquakeId, 10),
|
||
|
|
required: stringToBool(row.Required, true), // default TRUE
|
||
|
|
shopPrice: row.ShopPrice && row.ShopPrice !== ""
|
||
|
|
? parseFloat(row.ShopPrice)
|
||
|
|
: null,
|
||
|
|
pickedUp: stringToBool(row.PickedUp, false), // default FALSE
|
||
|
|
creatorId: null,
|
||
|
|
purchasedById: null,
|
||
|
|
}));
|
||
|
|
|
||
|
|
// 4. Bulk insert
|
||
|
|
await prisma.artefact.createMany({
|
||
|
|
data: artefacts,
|
||
|
|
skipDuplicates: true,
|
||
|
|
});
|
||
|
|
|
||
|
|
return NextResponse.json({
|
||
|
|
success: true,
|
||
|
|
count: artefacts.length,
|
||
|
|
});
|
||
|
|
} catch (error: any) {
|
||
|
|
console.error(error);
|
||
|
|
return NextResponse.json(
|
||
|
|
{ success: false, error: error.message },
|
||
|
|
{ status: 500 }
|
||
|
|
);
|
||
|
|
} finally {
|
||
|
|
await prisma.$disconnect();
|
||
|
|
}
|
||
|
|
}
|