68 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-05-19 14:36:29 +01:00
import { parse } from "csv-parse/sync";
2025-05-12 14:19:52 +01:00
import fs from "fs/promises";
2025-05-19 14:36:29 +01:00
import { NextResponse } from "next/server";
2025-05-12 14:19:52 +01:00
import path from "path";
2025-05-19 14:36:29 +01:00
import { PrismaClient } from "@prismaclient";
2025-05-12 14:19:52 +01:00
// CSV location (update filename as needed)
const csvFilePath = path.resolve(process.cwd(), "public/observatories.csv");
const prisma = new PrismaClient();
type CsvRow = {
2025-05-19 14:36:29 +01:00
Name: string;
Location: string;
Latitude: string;
Longitude: string;
DateEstablished?: string;
Functional: string;
SeismicSensorOnline?: string;
2025-05-12 14:19:52 +01:00
};
function stringToBool(val: string | undefined): boolean {
2025-05-19 14:36:29 +01:00
// Accepts "TRUE", "true", "True", etc.
if (!val) return false;
return /^true$/i.test(val.trim());
2025-05-12 14:19:52 +01:00
}
export async function POST() {
2025-05-19 14:36:29 +01:00
try {
// 1. Read file
const fileContent = await fs.readFile(csvFilePath, "utf8");
2025-05-12 14:19:52 +01:00
2025-05-19 14:36:29 +01:00
// 2. Parse CSV
const records: CsvRow[] = parse(fileContent, {
columns: true,
skip_empty_lines: true,
});
2025-05-12 14:19:52 +01:00
2025-05-19 14:36:29 +01:00
// 3. Map records to Prisma inputs
const observatories = records.map((row) => ({
name: row.Name,
location: row.Location,
latitude: row.Latitude,
longitude: row.Longitude,
dateEstablished: row.DateEstablished ? parseInt(row.DateEstablished, 10) : null,
functional: stringToBool(row.Functional),
seismicSensorOnline: row.SeismicSensorOnline ? stringToBool(row.SeismicSensorOnline) : true, // default true per schema
// todo add random selection of creatorId
2025-05-19 14:36:29 +01:00
creatorId: null,
}));
2025-05-12 14:19:52 +01:00
2025-05-19 14:36:29 +01:00
// 4. Bulk insert
await prisma.observatory.createMany({
data: observatories,
});
2025-05-12 14:19:52 +01:00
2025-05-19 14:36:29 +01:00
return NextResponse.json({
success: true,
count: observatories.length,
});
} catch (error: any) {
console.error(error);
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
} finally {
await prisma.$disconnect();
}
}