Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 30 additions & 9 deletions src/app/api/cohort/route.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@
// app/api/cohort/route.ts
import { NextResponse } from 'next/server';
import { MongoClient } from 'mongodb';

let cachedClient: MongoClient | null = null;

const uri = process.env.MONGO_URI!;
const client = new MongoClient(uri);
const dbName = 'cohortDB';
const collectionName = 'cohortData';
async function getClient(): Promise<MongoClient> {
if (cachedClient) return cachedClient;

const uri = process.env.MONGO_URI;
if (!uri) {
throw new Error('MONGO_URI environment variable is not set');
}

const client = new MongoClient(uri);
await client.connect();
cachedClient = client;
return client;
}

const DB_NAME = 'cohortDB';
const COLLECTION_NAME = 'cohortData';

export async function GET() {
try {
await client.connect();
const data = await client.db(dbName).collection(collectionName).find({}).toArray();
const client = await getClient();
const data = await client
.db(DB_NAME)
.collection(COLLECTION_NAME)
.find({})
.toArray();

return NextResponse.json(data);
} catch (error) {
return NextResponse.json({ error: 'Failed to fetch data' }, { status: 500 });
console.error('Failed to fetch cohort data:', error);
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to fetch data' },
{ status: 500 }
);
}
}
}