Spaces:
Runtime error
Runtime error
File size: 2,530 Bytes
c7fbc2e | 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 | import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
try {
const body = await req.json();
const { posts } = body; // Expecting { posts: [] }
if (!Array.isArray(posts) || posts.length === 0) {
return NextResponse.json({ error: "No posts provided" }, { status: 400 });
}
// Verify user owns all accounts involved
// Optimization: Fetch user's accounts once and verify IDs
const user = await prisma.user.findUnique({
where: { email: session.user.email },
include: { instagramAccounts: true },
});
if (!user) return NextResponse.json({ error: "User not found" }, { status: 404 });
const accountIds = new Set(user.instagramAccounts.map(a => a.id));
// Validate all posts
for (const post of posts) {
if (!post.instagramAccountId || !accountIds.has(post.instagramAccountId)) {
return NextResponse.json({ error: `Invalid account for post` }, { status: 403 });
}
}
// Transactional Create
// We need the created IDs to add to queue, so we might need $transaction returning them
const createdPosts = await prisma.$transaction(
posts.map(post => prisma.post.create({
data: {
caption: post.caption,
mediaUrl: post.mediaUrl,
mediaType: post.mediaType || "REELS",
coverUrl: post.coverUrl,
scheduledAt: post.scheduledAt ? new Date(post.scheduledAt) : null,
status: post.scheduledAt ? "SCHEDULED" : "DRAFT",
instagramAccountId: post.instagramAccountId,
}
}))
);
// With pg_cron, we just ensure status is SCHEDULED. The cron will pick them up.
// No explicit queue addition needed here.
return NextResponse.json({ count: createdPosts.length, ids: createdPosts.map(p => p.id) });
} catch (error) {
console.error("Bulk Create Error", error);
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}
|