File size: 1,601 Bytes
062a991 | 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 | import { eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { getDb } from "@/db";
import { posts, users } from "@/db/schema";
import { apiResponseError, readJsonObject, requireSameOrigin, requireUser } from "@/lib/api";
import { writeAuditLog } from "@/lib/audit";
const postSchema = z.object({
content: z.string().trim().min(1).max(3000),
mediaUrl: z.string().trim().url().optional(),
organizationId: z.string().uuid().optional(),
});
export async function GET() {
try {
const rows = await getDb().select({
post: posts,
author: { id: users.id, name: users.name, username: users.username, headline: users.headline, avatarUrl: users.avatarUrl },
}).from(posts).innerJoin(users, eq(users.id, posts.authorId));
return NextResponse.json({ posts: rows });
} catch (error) {
return apiResponseError(error);
}
}
export async function POST(request: NextRequest) {
try {
requireSameOrigin(request);
const user = await requireUser(request);
const payload = postSchema.parse(await readJsonObject(request));
const [post] = await getDb().insert(posts).values({
authorId: user.id,
organizationId: payload.organizationId,
content: payload.content,
mediaUrl: payload.mediaUrl,
}).returning();
await writeAuditLog({ tenantId: payload.organizationId ?? null, actorId: user.id, action: "post.created", entityType: "post", entityId: post.id });
return NextResponse.json({ post }, { status: 201 });
} catch (error) {
return apiResponseError(error);
}
}
|