Skip to content

Commit

Permalink
Merge pull request #51 from hack4impact-calpoly/document-api-routes-2
Browse files Browse the repository at this point in the history
Document api routes 2
  • Loading branch information
aarav27 authored Feb 28, 2025
2 parents 55b7d20 + 191b8e4 commit b4a36aa
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 51 deletions.
70 changes: 32 additions & 38 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

77 changes: 74 additions & 3 deletions src/app/api/document/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { NextRequest } from "next/server";
import dbConnect from "@/database/db";
import Document from "@/database/documentSchema";
import { createErrorResponse, createSuccessResponse } from "@/lib/response";
import mongoose from "mongoose";
import connectDB from "@/database/db";
import { createSuccessResponse, createErrorResponse } from "@/lib/response";

export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
try {
await dbConnect();
await connectDB();
const { id } = params;
const doc = await Document.findById(id);

Expand All @@ -18,3 +19,73 @@ export async function GET(request: NextRequest, { params }: { params: { id: stri
return createErrorResponse("Internal Server Error", error.message, 500);
}
}

export async function PUT(req: NextRequest, { params }: { params: { id: string } }) {
try {
await connectDB();
const { id } = params;

if (!mongoose.isValidObjectId(id)) {
return createErrorResponse("Invalid document ID", "Invalid document ID", 400);
}

const body = await req.json();
const { clerkId, eventId, s3DocId, ...updateFields } = body;

// Find document and verify ownership
const document = await Document.findOne({
_id: id,
clerkId: clerkId,
eventId: eventId,
s3DocId: s3DocId,
});

if (!document) {
return createErrorResponse("Document not found or unauthorized", "Document not found or unauthorized", 404);
}

// Update only the allowed fields
const updatedDocument = await Document.findByIdAndUpdate(
id,
{ ...updateFields },
{ new: true, runValidators: true },
);

return createSuccessResponse({ document: updatedDocument }, 200);
} catch (error) {
console.error("Error updating document:", error);
return createErrorResponse("Error updating document", "Error updating document", 500);
}
}

export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
try {
await connectDB();
const { id } = params;

if (!mongoose.isValidObjectId(id)) {
return createErrorResponse("Invalid document ID", "Invalid document ID", 400);
}

const body = await req.json();
const { clerkId, eventId, s3DocId } = body;

// Find document and verify ownership
const document = await Document.findOne({
_id: id,
clerkId: clerkId,
eventId: eventId,
s3DocId: s3DocId,
});

if (!document) {
return createErrorResponse("Document not found or unauthorized", "Document not found or unauthorized", 404);
}

await Document.findByIdAndDelete(id);
return createSuccessResponse({}, 200);
} catch (error) {
console.error("Error deleting document:", error);
return createErrorResponse("Error deleting document", "Error deleting document", 500);
}
}
34 changes: 24 additions & 10 deletions src/database/db.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,31 @@
import mongoose from "mongoose";

const url: string = process.env.MONGO_URI as string;
let connection: typeof mongoose;
const url: string | undefined = process.env.MONGO_URI;
if (!url) {
throw new Error("MONGO_URI is not defined in environment variables");
}

let isConnected = false; // Track connection status

/**
* Makes a connection to a MongoDB database. If a connection already exists, does nothing
* Call this function before all api routes
* @returns {Promise<typeof mongoose>}
*/
const connectDB = async () => {
if (!connection) {
connection = await mongoose.connect(url);
return connection;
if (isConnected) {
console.log("Using existing database connection");
return;
}

try {
const db = await mongoose.connect(url, {
dbName: "test", // Ensure this matches your database name in Compass
useNewUrlParser: true,
useUnifiedTopology: true,
} as any);

isConnected = true;
console.log("Connected to MongoDB");
return db;
} catch (error) {
console.error("MongoDB connection error:", error);
throw new Error("Failed to connect to MongoDB");
}
};

Expand Down

0 comments on commit b4a36aa

Please sign in to comment.