63 lines
1.9 KiB
TypeScript
63 lines
1.9 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";
|
||
|
|
|
||
|
|
// Define the path to your CSV file.
|
||
|
|
// Place your earthquakes.csv in your project root or `public` directory
|
||
|
|
const csvFilePath = path.resolve(process.cwd(), "public/earthquakes.csv");
|
||
|
|
|
||
|
|
const prisma = new PrismaClient();
|
||
|
|
|
||
|
|
type CsvRow = {
|
||
|
|
Date: string;
|
||
|
|
Magnitude: string;
|
||
|
|
Latitude: string;
|
||
|
|
Longitude: string;
|
||
|
|
Location: string;
|
||
|
|
Depth: string;
|
||
|
|
};
|
||
|
|
|
||
|
|
export async function POST() {
|
||
|
|
try {
|
||
|
|
// 1. Read the CSV file
|
||
|
|
const fileContent = await fs.readFile(csvFilePath, "utf8");
|
||
|
|
|
||
|
|
// 2. Parse the CSV
|
||
|
|
const records: CsvRow[] = parse(fileContent, {
|
||
|
|
columns: true,
|
||
|
|
skip_empty_lines: true
|
||
|
|
});
|
||
|
|
|
||
|
|
// 3. Transform each CSV row to Earthquake model
|
||
|
|
// Since your prisma model expects: name, date (DateTime), location, magnitude (float), depth (float). We'll fill casualties/creatorId as zero/null for now.
|
||
|
|
const earthquakes = records.map(row => {
|
||
|
|
// You may want to add better parsing & validation depending on your actual data
|
||
|
|
return {
|
||
|
|
date: new Date(row.Date),
|
||
|
|
location: row.Location,
|
||
|
|
magnitude: parseFloat(row.Magnitude),
|
||
|
|
latitude: row.Latitude,
|
||
|
|
longitude: row.Longitude,
|
||
|
|
depth: parseFloat(row.Depth.replace(" km", "")),
|
||
|
|
// todo add creatorId
|
||
|
|
creatorId: null
|
||
|
|
};
|
||
|
|
});
|
||
|
|
|
||
|
|
// 4. Bulk create earthquakes in database:
|
||
|
|
// Consider chunking if your CSV is large!
|
||
|
|
await prisma.earthquake.createMany({
|
||
|
|
data: earthquakes,
|
||
|
|
skipDuplicates: true, // in case the route is called twice
|
||
|
|
});
|
||
|
|
|
||
|
|
return NextResponse.json({ success: true, count: earthquakes.length });
|
||
|
|
} catch (error: any) {
|
||
|
|
console.error(error);
|
||
|
|
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
|
||
|
|
} finally {
|
||
|
|
await prisma.$disconnect();
|
||
|
|
}
|
||
|
|
}
|