77 lines
2.4 KiB
TypeScript
77 lines
2.4 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { apiAuthMiddleware } from "@utils/apiAuthMiddleware";
|
|
import { prisma } from "@utils/prisma";
|
|
import { writeFile } from "fs/promises";
|
|
import { join } from "path";
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const formData = await request.formData();
|
|
const name = formData.get("name") as string;
|
|
const type = formData.get("type") as string;
|
|
const description = formData.get("description") as string;
|
|
const earthquakeCode = formData.get("earthquakeCode") as string;
|
|
const warehouseArea = formData.get("warehouseArea") as string;
|
|
const image = formData.get("image") as File | null;
|
|
|
|
const authResult = await apiAuthMiddleware();
|
|
if ("user" in authResult === false) return authResult;
|
|
|
|
const { user } = authResult;
|
|
|
|
if (!name || !type || !description || !earthquakeCode || !warehouseArea) {
|
|
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
|
|
}
|
|
|
|
if (user.role !== "ADMIN" && user.role !== "SCIENTIST") {
|
|
return NextResponse.json({ error: "Not authorized" }, { status: 401 });
|
|
}
|
|
|
|
if (user.role === "SCIENTIST") {
|
|
const scientist = await prisma.scientist.findUnique({
|
|
where: {
|
|
userId: user.id,
|
|
},
|
|
include: {
|
|
subordinates: true,
|
|
},
|
|
});
|
|
|
|
if (!scientist || scientist.level !== "SENIOR") {
|
|
return NextResponse.json({ message: "Not authorised" }, { status: 401 });
|
|
}
|
|
}
|
|
|
|
const linkedEarthquake = await prisma.earthquake.findUnique({ where: { code: earthquakeCode } });
|
|
|
|
if (!linkedEarthquake) {
|
|
return NextResponse.json({ error: "Earthquake code not found" }, { status: 400 });
|
|
}
|
|
|
|
let imageName = "NoImageFound.PNG";
|
|
if (image) {
|
|
const buffer = Buffer.from(await image.arrayBuffer());
|
|
const extension = image.type === "image/jpeg" ? "jpg" : "png";
|
|
imageName = `${name}-${new Date().toLocaleDateString("en-GB")}.${extension}`;
|
|
const imagePath = join(process.cwd(), "public", imageName);
|
|
await writeFile(imagePath, buffer);
|
|
}
|
|
|
|
await prisma.artefact.create({
|
|
data: {
|
|
name,
|
|
type,
|
|
description,
|
|
earthquakeId: linkedEarthquake.id,
|
|
warehouseArea: warehouseArea,
|
|
imageName,
|
|
creatorId: user.id,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json({ message: "Artefact logged successfully" }, { status: 200 });
|
|
} catch (e: any) {
|
|
return NextResponse.json({ error: e.message }, { status: 500 });
|
|
}
|
|
}
|