68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
import { parse } from "csv-parse/sync";
|
|
import fs from "fs/promises";
|
|
import { NextResponse } from "next/server";
|
|
import path from "path";
|
|
|
|
import { PrismaClient } from "@prismaclient";
|
|
|
|
// CSV location (update filename as needed)
|
|
const csvFilePath = path.resolve(process.cwd(), "public/observatories.csv");
|
|
const prisma = new PrismaClient();
|
|
|
|
type CsvRow = {
|
|
Name: string;
|
|
Location: string;
|
|
Latitude: string;
|
|
Longitude: string;
|
|
DateEstablished?: string;
|
|
Functional: string;
|
|
SeismicSensorOnline?: string;
|
|
};
|
|
|
|
function stringToBool(val: string | undefined): boolean {
|
|
// Accepts "TRUE", "true", "True", etc.
|
|
if (!val) return false;
|
|
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 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
|
|
creatorId: null,
|
|
}));
|
|
|
|
// 4. Bulk insert
|
|
await prisma.observatory.createMany({
|
|
data: observatories,
|
|
});
|
|
|
|
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();
|
|
}
|
|
}
|