Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | import { NextRequest, NextResponse } from "next/server";
import { connectDB } from "@/lib/mongodb";
import { requireAuth } from "@/lib/session";
import Post from "@/models/Post";
import AuditLog from "@/models/AuditLog";
// GET /api/posts - List posts with optional filtering
export async function GET(request: NextRequest) {
try {
const session = await requireAuth();
await connectDB();
const { searchParams } = new URL(request.url);
const categoryId = searchParams.get("categoryId");
const authorId = searchParams.get("authorId");
const limit = parseInt(searchParams.get("limit") || "20");
const cursor = searchParams.get("cursor");
const query: Record<string, unknown> = {
deletedAt: { $exists: false },
};
// Filter by visibility
if (authorId && authorId === session.user.id) {
// User can see their own private posts
query.authorId = authorId;
} else {
// Others can only see public and members posts
query.visibility = { $in: ["public", "members"] };
}
if (categoryId) {
query.categoryId = categoryId;
}
if (authorId && authorId !== session.user.id) {
query.authorId = authorId;
}
if (cursor) {
query._id = { $lt: cursor };
}
const posts = await Post.find(query)
.select("title summary tags visibility createdAt updatedAt authorId categoryId")
.sort({ createdAt: -1 })
.limit(limit + 1)
.populate("authorId", "name email image")
.populate("categoryId", "name slug description");
const hasMore = posts.length > limit;
const data = hasMore ? posts.slice(0, limit) : posts;
const nextCursor = hasMore && data.length > 0
? (data[data.length - 1] as { _id: { toString(): string } })._id.toString()
: null;
return NextResponse.json({
data,
nextCursor,
});
} catch (error) {
if (error instanceof Error && error.message === "Unauthorized") {
return NextResponse.json(
{ error: { code: "UNAUTHORIZED", message: "Authentication required" } },
{ status: 401 }
);
}
console.error("Error fetching posts:", error);
return NextResponse.json(
{
error: {
code: "INTERNAL_ERROR",
message: "Failed to fetch posts",
},
},
{ status: 500 }
);
}
}
// POST /api/posts - Create a new post
export async function POST(request: NextRequest) {
try {
const session = await requireAuth();
await connectDB();
const body = await request.json();
const {
categoryId,
title,
summary,
body: postBody,
tags,
visibility,
allowComments,
} = body;
if (!categoryId || !title || !summary || !postBody) {
return NextResponse.json(
{
error: {
code: "VALIDATION_ERROR",
message: "Category, title, summary, and body are required",
},
},
{ status: 400 }
);
}
const post = await Post.create({
authorId: session.user.id,
categoryId,
title,
summary,
body: postBody,
tags: tags || [],
visibility: visibility || "public",
allowComments: allowComments !== undefined ? allowComments : true,
});
// Create audit log
await AuditLog.create({
entityType: "post",
entityId: post._id,
action: "created",
userId: session.user.id,
payload: { title, categoryId },
});
const populatedPost = await Post.findById(post._id)
.select("-__v")
.populate("authorId", "name email image")
.populate("categoryId", "name slug description");
return NextResponse.json({ data: populatedPost }, { status: 201 });
} catch (error) {
if (error instanceof Error && error.message === "Unauthorized") {
return NextResponse.json(
{ error: { code: "UNAUTHORIZED", message: "Authentication required" } },
{ status: 401 }
);
}
console.error("Error creating post:", error);
return NextResponse.json(
{
error: {
code: "INTERNAL_ERROR",
message: "Failed to create post",
},
},
{ status: 500 }
);
}
}
|