Spaces:
Configuration error
Configuration error
| import { NextRequest } from 'next/server'; | |
| import { db } from '@/lib/db'; | |
| import { getAuthUser } from '@/lib/auth'; | |
| import { apiHandler, errorResponse, successResponse, paginatedResponse, getPagination, getSorting, getFilters } from '@/lib/api-utils'; | |
| /** GET /api/posts - List posts with pagination, filtering, sorting */ | |
| export const GET = apiHandler(async (request: NextRequest) => { | |
| const authUser = await getAuthUser(request); | |
| if (!authUser) return errorResponse('Authentication required', 401); | |
| const { page, limit, skip } = getPagination(request); | |
| const orderBy = getSorting(request); | |
| const filters = getFilters(request, ['status', 'approvalStatus', 'campaignId']); | |
| const where: Record<string, unknown> = { userId: authUser.userId }; | |
| if (filters.status) where.status = filters.status; | |
| if (filters.approvalStatus) where.approvalStatus = filters.approvalStatus; | |
| if (filters.campaignId) where.campaignId = filters.campaignId; | |
| const [posts, total] = await Promise.all([ | |
| db.post.findMany({ where, skip, take: limit, orderBy, include: { postAccounts: { include: { account: true } }, postMedia: { include: { media: true } }, campaign: { select: { id: true, name: true } } } }), | |
| db.post.count({ where }), | |
| ]); | |
| return paginatedResponse(posts, page, limit, total); | |
| }); | |
| /** POST /api/posts - Create new post */ | |
| export const POST = apiHandler(async (request: NextRequest) => { | |
| const authUser = await getAuthUser(request); | |
| if (!authUser) return errorResponse('Authentication required', 401); | |
| const body = await request.json(); | |
| const { title, campaignId, captionDefault, hashtags, scheduledAt, timezone, accountIds, mediaIds } = body; | |
| const post = await db.post.create({ | |
| data: { | |
| userId: authUser.userId, | |
| title: title || 'Untitled Post', | |
| campaignId: campaignId || null, | |
| captionDefault, | |
| hashtags: hashtags ? JSON.stringify(hashtags) : null, | |
| scheduledAt: scheduledAt ? new Date(scheduledAt) : null, | |
| timezone: timezone || 'UTC', | |
| status: scheduledAt ? 'SCHEDULED' : 'DRAFT', | |
| postAccounts: accountIds?.length ? { create: accountIds.map((accountId: string) => ({ accountId })) } : undefined, | |
| postMedia: mediaIds?.length ? { create: mediaIds.map((mediaId: string, index: number) => ({ mediaId, position: index })) } : undefined, | |
| }, | |
| include: { postAccounts: { include: { account: true } }, postMedia: { include: { media: true } } }, | |
| }); | |
| await db.auditLog.create({ data: { userId: authUser.userId, action: 'POST_CREATED', resource: 'Post', resourceId: post.id } }); | |
| return successResponse(post, 201); | |
| }); | |