v1
This commit is contained in:
95
src/app/api/delete-observation/[id]/route.ts
Normal file
95
src/app/api/delete-observation/[id]/route.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function DELETE(
|
||||
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');
|
||||
|
||||
// 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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the document
|
||||
const result = await collection.deleteOne(filter);
|
||||
|
||||
await client.close();
|
||||
|
||||
if (result.deletedCount === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Failed to delete observation'
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Observation deleted successfully'
|
||||
});
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Delete observation error:', error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Failed to delete observation',
|
||||
message: error.message
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user