@@ -3,23 +3,19 @@ import { NextResponse } from 'next/server';
33import mongoose from 'mongoose' ;
44import { Score } from '@/app/models/Score' ;
55
6- // We rely on an environment variable MONGO_URI set in Amplify / hosting environment.
7- // Earlier build logs showed SSM secrets failing to load, so provide defensive handling.
8- const DB_URI = process . env . MONGO_URI ;
6+ // Ensure Node.js runtime (not Edge) so we can use Mongoose
7+ export const runtime = 'nodejs' ;
98
109// Reuse a cached connection across hot reloads / lambda invocations to avoid creating many sockets.
1110declare global {
1211 // eslint-disable-next-line no-var
1312 var __MONGO_READY : Promise < typeof mongoose > | undefined ;
1413}
1514
16- async function connectToDatabase ( ) {
17- if ( ! DB_URI ) {
18- throw new Error ( 'Missing MONGO_URI environment variable' ) ;
19- }
15+ async function connectToDatabase ( uri : string ) {
2016 if ( mongoose . connection . readyState === 1 ) return ; // already connected
2117 if ( ! global . __MONGO_READY ) {
22- global . __MONGO_READY = mongoose . connect ( DB_URI ) . catch ( ( err ) => {
18+ global . __MONGO_READY = mongoose . connect ( uri ) . catch ( ( err ) => {
2319 // Reset so future calls can retry
2420 global . __MONGO_READY = undefined ;
2521 throw err ;
@@ -30,7 +26,7 @@ async function connectToDatabase() {
3026
3127// Handle POST request to save a score
3228export async function POST ( req : Request ) {
33- // Validate env up front for clearer error surface
29+ const DB_URI = process . env . MONGO_URI ; // read at request time to avoid build-time inlining issues
3430 if ( ! DB_URI ) {
3531 return NextResponse . json ( { error : 'Server not configured (MONGO_URI missing)' } , { status : 503 } ) ;
3632 }
@@ -42,7 +38,7 @@ export async function POST(req: Request) {
4238 if ( typeof score !== 'number' || ! Number . isFinite ( score ) || score < 0 ) {
4339 return NextResponse . json ( { error : 'Invalid score' } , { status : 400 } ) ;
4440 }
45- await connectToDatabase ( ) ;
41+ await connectToDatabase ( DB_URI ) ;
4642 const newScore = new Score ( { name : name . trim ( ) , score : Math . floor ( score ) } ) ;
4743 await newScore . save ( ) ;
4844 return NextResponse . json ( { message : 'Score saved' , score : newScore } , { status : 201 } ) ;
@@ -54,11 +50,12 @@ export async function POST(req: Request) {
5450
5551// Handle GET request to fetch all scores
5652export async function GET ( ) {
53+ const DB_URI = process . env . MONGO_URI ; // read at request time
5754 if ( ! DB_URI ) {
5855 return NextResponse . json ( { error : 'Server not configured (MONGO_URI missing)' } , { status : 503 } ) ;
5956 }
6057 try {
61- await connectToDatabase ( ) ;
58+ await connectToDatabase ( DB_URI ) ;
6259 const scores = await Score . find ( ) . sort ( { score : - 1 } ) . limit ( 100 ) . lean ( ) ;
6360 return NextResponse . json ( scores ) ;
6461 } catch ( err : any ) {
0 commit comments