From 885e694ad29c864b0e376e823cdea10fa54b3247 Mon Sep 17 00:00:00 2001 From: Tim Howitz Date: Tue, 20 May 2025 18:26:40 +0100 Subject: [PATCH] Converted to a prisma singleton --- src/app/api/earthquakes/route.ts | 8 +--- src/app/api/get-user/route.ts | 6 +-- src/app/api/import-earthquakes/route.ts | 6 +-- src/app/api/import-observatories/route.ts | 5 +-- src/app/api/import-requests/route.ts | 6 +-- src/app/api/import-scientists/route.ts | 5 +-- src/app/api/import-users/route.ts | 5 +-- src/app/api/login/route.ts | 8 +--- src/app/api/observatories/route.ts | 11 +----- src/app/api/signup/route.ts | 45 ++++++++--------------- src/app/api/warehouse/route.ts | 6 +-- src/utils/apiAuthMiddleware.ts | 3 +- src/utils/prisma.ts | 9 +++++ 13 files changed, 36 insertions(+), 87 deletions(-) create mode 100644 src/utils/prisma.ts diff --git a/src/app/api/earthquakes/route.ts b/src/app/api/earthquakes/route.ts index c44dbd5..c12f380 100644 --- a/src/app/api/earthquakes/route.ts +++ b/src/app/api/earthquakes/route.ts @@ -1,10 +1,6 @@ import { NextResponse } from "next/server"; -import { PrismaClient } from "@prismaclient"; - -const usingPrisma = false; -let prisma: PrismaClient; -if (usingPrisma) prisma = new PrismaClient(); +import { prisma } from "@utils/prisma"; export async function POST(req: Request) { try { @@ -33,7 +29,5 @@ export async function POST(req: Request) { } catch (error) { console.error("Error in earthquakes endpoint:", error); return NextResponse.json({ message: "Internal Server Error" }, { status: 500 }); - } finally { - if (usingPrisma) await prisma.$disconnect(); } } diff --git a/src/app/api/get-user/route.ts b/src/app/api/get-user/route.ts index c2f97e3..0904559 100644 --- a/src/app/api/get-user/route.ts +++ b/src/app/api/get-user/route.ts @@ -1,10 +1,8 @@ import { NextResponse } from "next/server"; import { cookies } from "next/headers"; import { env } from "@utils/env"; -import { PrismaClient } from "@prisma/client"; import { verifyJwt } from "@utils/verifyJwt"; - -const prisma = new PrismaClient(); +import { prisma } from "@utils/prisma"; export async function POST(req: Request) { let cookieStore; @@ -41,7 +39,5 @@ export async function POST(req: Request) { console.error("Error in user endpoint:", error); cookieStore?.delete("jwt"); // Delete JWT cookie on error return NextResponse.json({ message: "Internal Server Error" }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/app/api/import-earthquakes/route.ts b/src/app/api/import-earthquakes/route.ts index cc9b564..7712819 100644 --- a/src/app/api/import-earthquakes/route.ts +++ b/src/app/api/import-earthquakes/route.ts @@ -1,13 +1,11 @@ import { parse } from "csv-parse/sync"; import fs from "fs/promises"; import { NextResponse } from "next/server"; +import { prisma } from "@utils/prisma"; import path from "path"; -import { PrismaClient } from "@prismaclient"; - // Path to your earthquakes.csv const csvFilePath = path.resolve(process.cwd(), "public/earthquakes.csv"); -const prisma = new PrismaClient(); type CsvRow = { Date: string; @@ -50,7 +48,5 @@ export async function POST() { } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/app/api/import-observatories/route.ts b/src/app/api/import-observatories/route.ts index ca21887..fccd04c 100644 --- a/src/app/api/import-observatories/route.ts +++ b/src/app/api/import-observatories/route.ts @@ -3,11 +3,10 @@ import fs from "fs/promises"; import { NextResponse } from "next/server"; import path from "path"; -import { PrismaClient } from "@prismaclient"; +import { prisma } from "@utils/prisma"; // CSV location (update filename as needed) const csvFilePath = path.resolve(process.cwd(), "public/observatories.csv"); -const prisma = new PrismaClient(); type CsvRow = { Name: string; @@ -61,7 +60,5 @@ export async function POST() { } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/app/api/import-requests/route.ts b/src/app/api/import-requests/route.ts index 4b63309..021ed92 100644 --- a/src/app/api/import-requests/route.ts +++ b/src/app/api/import-requests/route.ts @@ -3,10 +3,8 @@ import fs from "fs/promises"; import { NextResponse } from "next/server"; import path from "path"; -import { PrismaClient } from "@prismaclient"; - +import { prisma } from "@utils/prisma"; const csvFilePath = path.resolve(process.cwd(), "public/requests.csv"); -const prisma = new PrismaClient(); type RequestType = "NEW_USER" | "CHANGE_LEVEL" | "DELETE"; type RequestOutcome = "FULFILLED" | "REJECTED" | "IN_PROGRESS" | "CANCELLED" | "OTHER"; @@ -56,7 +54,5 @@ export async function POST() { } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/app/api/import-scientists/route.ts b/src/app/api/import-scientists/route.ts index 83c229b..b91cf52 100644 --- a/src/app/api/import-scientists/route.ts +++ b/src/app/api/import-scientists/route.ts @@ -3,11 +3,10 @@ import fs from "fs/promises"; import { NextResponse } from "next/server"; import path from "path"; -import { PrismaClient } from "@prismaclient"; +import { prisma } from "@utils/prisma"; // Path to CSV file const csvFilePath = path.resolve(process.cwd(), "public/scientists.csv"); -const prisma = new PrismaClient(); type CsvRow = { Name: string; @@ -53,7 +52,5 @@ export async function POST() { } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/app/api/import-users/route.ts b/src/app/api/import-users/route.ts index 0ffe5ed..1e4f166 100644 --- a/src/app/api/import-users/route.ts +++ b/src/app/api/import-users/route.ts @@ -3,11 +3,10 @@ import fs from "fs/promises"; import { NextResponse } from "next/server"; import path from "path"; -import { PrismaClient } from "@prismaclient"; +import { prisma } from "@utils/prisma"; // Path to users.csv - adjust as needed const csvFilePath = path.resolve(process.cwd(), "public/users.csv"); -const prisma = new PrismaClient(); type CsvRow = { Name: string; @@ -51,7 +50,5 @@ export async function POST() { } catch (error: any) { console.error(error); return NextResponse.json({ success: false, error: error.message }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/app/api/login/route.ts b/src/app/api/login/route.ts index 06b8657..a374d38 100644 --- a/src/app/api/login/route.ts +++ b/src/app/api/login/route.ts @@ -2,15 +2,11 @@ import bcryptjs from "bcryptjs"; import { SignJWT } from "jose"; import { NextResponse } from "next/server"; -import { PrismaClient } from "@prismaclient"; import { env } from "@utils/env"; +import { prisma } from "@utils/prisma"; import { findUserByEmail, readUserCsv, User } from "../functions/csvReadWrite"; -const usingPrisma = false; -let prisma: PrismaClient; -if (usingPrisma) prisma = new PrismaClient(); - export async function POST(req: Request) { try { const { email, password } = await req.json(); // Parse incoming JSON data @@ -67,7 +63,5 @@ export async function POST(req: Request) { } catch (error) { console.error("Error in signup endpoint:", error); return NextResponse.json({ message: "Internal Server Error" }, { status: 500 }); - } finally { - if (usingPrisma) await prisma.$disconnect(); } } diff --git a/src/app/api/observatories/route.ts b/src/app/api/observatories/route.ts index 28258fe..809efe5 100644 --- a/src/app/api/observatories/route.ts +++ b/src/app/api/observatories/route.ts @@ -1,10 +1,6 @@ import { NextResponse } from "next/server"; -import { PrismaClient } from "@prismaclient"; - -const usingPrisma = false; -let prisma: PrismaClient; -if (usingPrisma) prisma = new PrismaClient(); +import { prisma } from "@utils/prisma"; export async function GET(request: Request) { try { @@ -36,8 +32,7 @@ export async function GET(request: Request) { ]; // todo get earthquakes associated with observatories - let observatories; - if (usingPrisma) observatories = await prisma.observatory.findMany(); + const observatories = await prisma.observatory.findMany(); if (observatories) { return NextResponse.json({ message: "Got observatories successfully", observatories }, { status: 200 }); @@ -48,7 +43,5 @@ export async function GET(request: Request) { } catch (error) { console.error("Error in observatories endpoint:", error); return NextResponse.json({ message: "Internal Server Error" }, { status: 500 }); - } finally { - if (usingPrisma) await prisma.$disconnect(); } } diff --git a/src/app/api/signup/route.ts b/src/app/api/signup/route.ts index b7449c3..a62510b 100644 --- a/src/app/api/signup/route.ts +++ b/src/app/api/signup/route.ts @@ -2,15 +2,11 @@ import bcryptjs from "bcryptjs"; import { SignJWT } from "jose"; import { NextResponse } from "next/server"; -import { PrismaClient } from "@prismaclient"; +import { prisma } from "@utils/prisma"; import { env } from "@utils/env"; import { findUserByEmail, passwordStrengthCheck, readUserCsv, User, writeUserCsv } from "../functions/csvReadWrite"; -const usingPrisma = false; -let prisma: PrismaClient; -if (usingPrisma) prisma = new PrismaClient(); - export async function POST(req: Request) { try { const { email, password, name } = await req.json(); // Parse incoming JSON data @@ -23,17 +19,11 @@ export async function POST(req: Request) { console.log("Email:", email); // ! remove console.log("Password:", password); // ! remove - let foundUser; - - if (usingPrisma) { - foundUser = await prisma.user.findUnique({ - where: { - email: email, // use the email to uniquely identify the user - }, - }); - } else { - foundUser = findUserByEmail(userData, email); - } + const foundUser = await prisma.user.findUnique({ + where: { + email: email, // use the email to uniquely identify the user + }, + }); if (foundUser) { return NextResponse.json({ message: "Sorry, this email is already in use" }, { status: 409 }); @@ -58,20 +48,15 @@ export async function POST(req: Request) { } else { try { const passwordHash = await bcryptjs.hash(password, 10); - let user; - if (usingPrisma) { - // todo add sending back user - user = await prisma.user.create({ - data: { - name, - email, - passwordHash, - }, - }); - } else { - user = { name, email, password: passwordHash, accessLevel }; - userData.push(user); - } + // todo add sending back user + const user = await prisma.user.create({ + data: { + name, + email, + passwordHash, + }, + }); + await writeUserCsv(userData); const secret = new TextEncoder().encode(env.JWT_SECRET_KEY); diff --git a/src/app/api/warehouse/route.ts b/src/app/api/warehouse/route.ts index 1315238..4dd3ef6 100644 --- a/src/app/api/warehouse/route.ts +++ b/src/app/api/warehouse/route.ts @@ -2,14 +2,12 @@ import { NextResponse } from "next/server"; import { JWTPayload } from "@appTypes/JWT"; import { cookies } from "next/headers"; -import { PrismaClient } from "@prismaclient"; +import { prisma } from "@utils/prisma"; import { env } from "@utils/env"; import { verifyJwt } from "@utils/verifyJwt"; import { ExtendedArtefact } from "@appTypes/ApiTypes"; import { apiAuthMiddleware } from "@utils/apiAuthMiddleware"; -const prisma = new PrismaClient(); - export async function POST(req: Request) { try { const authResult = await apiAuthMiddleware(); @@ -40,7 +38,5 @@ export async function POST(req: Request) { } catch (error) { console.error("Error in artefacts endpoint:", error); return NextResponse.json({ message: "Internal Server Error" }, { status: 500 }); - } finally { - await prisma.$disconnect(); } } diff --git a/src/utils/apiAuthMiddleware.ts b/src/utils/apiAuthMiddleware.ts index 5215914..9d07052 100644 --- a/src/utils/apiAuthMiddleware.ts +++ b/src/utils/apiAuthMiddleware.ts @@ -1,11 +1,10 @@ import { NextResponse } from "next/server"; import { cookies } from "next/headers"; import { verifyJwt } from "@utils/verifyJwt"; -import { PrismaClient } from "@prismaclient"; import type { JWTPayload } from "@/types/JWT"; import { env } from "@utils/env"; -const prisma = new PrismaClient(); +import { prisma } from "@utils/prisma"; export async function apiAuthMiddleware() { const cookieStore = await cookies(); diff --git a/src/utils/prisma.ts b/src/utils/prisma.ts new file mode 100644 index 0000000..93754e1 --- /dev/null +++ b/src/utils/prisma.ts @@ -0,0 +1,9 @@ +import { PrismaClient } from "@prisma/client"; + +declare global { + var prisma: PrismaClient | undefined; +} + +const prisma = process.env.NODE_ENV === "production" ? new PrismaClient() : global.prisma ?? (global.prisma = new PrismaClient()); + +export { prisma };