Skip to content

Commit

Permalink
Added add comment route
Browse files Browse the repository at this point in the history
  • Loading branch information
ShivaBhattacharjee committed Nov 8, 2023
1 parent e316c7d commit b08b2de
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/app/api/comment/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from "next/server";
import Comment from "@/model/comment.model";
import { connect } from "@/database/db";
import { Error } from "@/types/ErrorTypes";
import { getDataFromJwt } from "@/helper/jwtData";
import User from "@/model/user.model";
connect();

export async function POST(request: NextRequest) {
try {
const userID = getDataFromJwt(request);
const reqBody = await request.json();
const { animeId, text, userId } = reqBody;
const user = await User.findOne({ _id: userID }).select("-password");
if (!user) {
return NextResponse.json(
{
error: "No user found",
},
{
status: 401,
},
);
}
const newComment = new Comment({
userId,
animeId,
text,
});
await newComment.save();
return NextResponse.json({
message: "Comment added",
});
} catch (error: unknown) {
const ErrorMsg = error as Error;
return NextResponse.json({ error: ErrorMsg.message });
}
}
29 changes: 29 additions & 0 deletions src/model/comment.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import mongoose from "mongoose";

const commentSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: [true, "Please provide a user ID"],
},
animeId: {
type: String,
required: [true, "Please provide an anime ID"],
},
text: {
type: String,
required: [true, "Please provide a comment text"],
},
timestamp: {
type: Date,
default: Date.now,
},
likes: {
type: Number,
default: 0,
},
});

const Comment = mongoose.model("Comment", commentSchema);

export default Comment;

0 comments on commit b08b2de

Please sign in to comment.