v1
This commit is contained in:
73
src/app/api/get-observations/route.ts
Normal file
73
src/app/api/get-observations/route.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const page = parseInt(searchParams.get('page') || '1');
|
||||
const limit = parseInt(searchParams.get('limit') || '12');
|
||||
const framework = searchParams.get('framework');
|
||||
const learningArea = searchParams.get('learningArea');
|
||||
const subLearningArea = searchParams.get('subLearningArea');
|
||||
|
||||
const { MongoClient } = require('mongodb');
|
||||
const uri = process.env.MONGODB_URI || 'mongodb://localhost/beanstalk';
|
||||
const client = new MongoClient(uri);
|
||||
await client.connect();
|
||||
const db = client.db('beanstalk');
|
||||
const collection = db.collection('observations');
|
||||
|
||||
// Build filter query
|
||||
let filter: any = {};
|
||||
|
||||
if (framework) {
|
||||
filter['indicators.developmentAreas.framework'] = framework.trim();
|
||||
}
|
||||
|
||||
if (learningArea) {
|
||||
filter['indicators.developmentAreas.learningArea'] = learningArea.trim();
|
||||
}
|
||||
|
||||
if (subLearningArea) {
|
||||
filter['indicators.developmentAreas.subLearningArea'] = subLearningArea.trim();
|
||||
}
|
||||
|
||||
// Get total count for pagination
|
||||
const totalCount = await collection.countDocuments(filter);
|
||||
|
||||
// Calculate skip value for pagination
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
// Fetch observations with pagination and sort by createdAt (newest first)
|
||||
const documents = await collection
|
||||
.find(filter)
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit)
|
||||
.toArray();
|
||||
|
||||
await client.close();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: documents,
|
||||
pagination: {
|
||||
currentPage: page,
|
||||
totalPages: Math.ceil(totalCount / limit),
|
||||
totalCount: totalCount,
|
||||
limit: limit,
|
||||
hasNextPage: page < Math.ceil(totalCount / limit),
|
||||
hasPrevPage: page > 1
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching observations:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Failed to fetch observations',
|
||||
message: error.message
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user