v1
This commit is contained in:
110
src/app/api/update-observation/[id]/route.ts
Normal file
110
src/app/api/update-observation/[id]/route.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const id = params.id;
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'No ID provided'
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { MongoClient, ObjectId } = 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');
|
||||
|
||||
const body = await request.json();
|
||||
|
||||
// Try to find the document first to determine the correct _id format
|
||||
let document = await collection.findOne({ _id: id });
|
||||
let filter;
|
||||
|
||||
if (document) {
|
||||
// Found with string ID
|
||||
filter = { _id: id };
|
||||
} else {
|
||||
// Try with ObjectId
|
||||
try {
|
||||
const objectId = new ObjectId(id);
|
||||
document = await collection.findOne({ _id: objectId });
|
||||
if (document) {
|
||||
filter = { _id: objectId };
|
||||
} else {
|
||||
await client.close();
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Observation not found'
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
await client.close();
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Invalid ID format'
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Update observation
|
||||
const result = await collection.updateOne(
|
||||
filter,
|
||||
{
|
||||
$set: {
|
||||
...body,
|
||||
updatedAt: new Date()
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if (result.matchedCount === 0) {
|
||||
await client.close();
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Observation not found'
|
||||
},
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch updated document
|
||||
const updatedDocument = await collection.findOne(filter);
|
||||
|
||||
await client.close();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: updatedDocument,
|
||||
message: 'Observation updated successfully'
|
||||
});
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Error updating observation:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Failed to update observation',
|
||||
message: error.message
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user