apix/app/api/meta/generate/route.ts
Khoa.vo 8741e3b89f
Some checks are pending
CI / build (18.x) (push) Waiting to run
CI / build (20.x) (push) Waiting to run
feat: Initial commit with multi-provider image generation
2026-01-05 13:50:35 +07:00

60 lines
2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { MetaAIClient } from '@/lib/providers/meta-client';
export async function POST(req: NextRequest) {
try {
const { prompt, cookies, imageCount = 4 } = await req.json();
if (!prompt) {
return NextResponse.json({ error: "Prompt is required" }, { status: 400 });
}
if (!cookies) {
return NextResponse.json(
{ error: "Meta AI cookies required. Configure in Settings." },
{ status: 401 }
);
}
console.log(`[Meta AI Route] Generating images for: "${prompt.substring(0, 30)}..."`);
const client = new MetaAIClient({ cookies });
const results = await client.generate(prompt, imageCount);
// Download images as base64 for storage
const images = await Promise.all(
results.map(async (img) => {
let base64 = img.data;
if (!base64 && img.url) {
try {
base64 = await client.downloadAsBase64(img.url);
} catch (e) {
console.warn("[Meta AI Route] Failed to download image:", e);
}
}
return {
data: base64 || '',
url: img.url,
prompt: img.prompt,
model: img.model,
aspectRatio: '1:1' // Meta AI default
};
})
);
const validImages = images.filter(img => img.data || img.url);
if (validImages.length === 0) {
throw new Error("No valid images generated");
}
return NextResponse.json({ images: validImages });
} catch (error: any) {
console.error("[Meta AI Route] Error:", error);
return NextResponse.json(
{ error: error.message || "Meta AI generation failed" },
{ status: 422 } // Use 422 instead of 500 to avoid Next.js rendering error pages
);
}
}