feat: complete dynamic JSON-driven photo tools frontend connected to FastAPI backend
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getToolById, getToolBySlug } from '@/lib/config/loader';
|
||||
import { getEndpointById } from '@/lib/catalog/loader';
|
||||
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
|
||||
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const maxDuration = 60; // 60 seconds request timeout per PRD §4.1
|
||||
|
||||
export async function POST(req: NextRequest, { params }: { params: { toolId: string } }) {
|
||||
const toolIdentifier = params.toolId;
|
||||
const tool = getToolById(toolIdentifier) || getToolBySlug(toolIdentifier);
|
||||
|
||||
if (!tool) {
|
||||
return NextResponse.json(
|
||||
{ state: 'failed', error: { code: 'TOOL_NOT_FOUND', messageKey: 'toolNotFound', retryable: false } },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!tool.tryIt || !tool.tryIt.enabled) {
|
||||
return NextResponse.json(
|
||||
{ state: 'unavailable', messageKey: 'toolUnavailable' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const endpointId = tool.tryIt.endpointRef?.id;
|
||||
const endpoint = endpointId ? getEndpointById(endpointId) : undefined;
|
||||
|
||||
if (!endpoint || !endpoint.enabled || !endpoint.publicTry || isCircuitOpen(endpoint.id)) {
|
||||
return NextResponse.json(
|
||||
{ state: 'unavailable', messageKey: 'toolTemporarilyUnavailable' },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
// Rate Limiting & Abuse Prevention
|
||||
const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || '127.0.0.1';
|
||||
let visitorId = req.cookies.get('photoai_vid')?.value;
|
||||
let isNewVisitor = false;
|
||||
if (!visitorId) {
|
||||
visitorId = 'v_' + Math.random().toString(36).substring(2, 15);
|
||||
isNewVisitor = true;
|
||||
}
|
||||
|
||||
const rateCheck = checkRateLimits(visitorId, ip);
|
||||
if (!rateCheck.allowed) {
|
||||
const res = NextResponse.json(
|
||||
{
|
||||
state: 'limit',
|
||||
messageKey: rateCheck.reason === 'budget_exhausted' ? 'dailyBudgetExceeded' : 'freeTriesExhausted',
|
||||
remainingToday: 0,
|
||||
},
|
||||
{ status: 429 }
|
||||
);
|
||||
if (isNewVisitor) {
|
||||
res.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: 60 * 60 * 24 * 30, httpOnly: true });
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
try {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get('image') as File | null;
|
||||
const variantId = (formData.get('variant') as string) || tool.tryIt.endpointRef?.defaultVariant;
|
||||
const optionsRaw = formData.get('options') as string | null;
|
||||
let options: Record<string, any> = {};
|
||||
if (optionsRaw) {
|
||||
try {
|
||||
options = JSON.parse(optionsRaw);
|
||||
} catch {
|
||||
// Ignore malformed options
|
||||
}
|
||||
}
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json(
|
||||
{ state: 'failed', error: { code: 'NO_IMAGE', messageKey: 'noImageProvided', retryable: false } },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Size limit check
|
||||
const maxBytes = (tool.tryIt.limits?.maxMB || 12) * 1024 * 1024;
|
||||
if (file.size > maxBytes) {
|
||||
return NextResponse.json(
|
||||
{ state: 'failed', error: { code: 'FILE_TOO_LARGE', messageKey: 'fileTooLarge', retryable: false } },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
// File signature verification (JPEG, PNG, WEBP)
|
||||
const sigCheck = checkFileSignature(buffer);
|
||||
if (!sigCheck.valid) {
|
||||
return NextResponse.json(
|
||||
{ state: 'failed', error: { code: 'INVALID_SIGNATURE', messageKey: 'invalidFileType', retryable: false } },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Record rate-limit usage
|
||||
recordUsage(visitorId, ip);
|
||||
|
||||
// Call backend or mock engine
|
||||
const { buffer: resultBuffer, contentType } = await executeBackendTryIt(
|
||||
endpoint,
|
||||
tool.id,
|
||||
variantId,
|
||||
buffer,
|
||||
file.name || 'image.jpg',
|
||||
options
|
||||
);
|
||||
|
||||
const response = new NextResponse(new Uint8Array(resultBuffer), {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Length': resultBuffer.length.toString(),
|
||||
'Cache-Control': 'no-store, no-cache, must-revalidate',
|
||||
'X-Remaining-Tries': rateCheck.remainingToday.toString(),
|
||||
},
|
||||
});
|
||||
|
||||
if (isNewVisitor) {
|
||||
response.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: 60 * 60 * 24 * 30, httpOnly: true });
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (err: any) {
|
||||
console.error(`[API /try/${toolIdentifier}] Error:`, err);
|
||||
return NextResponse.json(
|
||||
{
|
||||
state: 'failed',
|
||||
error: {
|
||||
code: 'PROCESSING_ERROR',
|
||||
messageKey: 'processingError',
|
||||
message: err.message || 'Internal processing error',
|
||||
retryable: true,
|
||||
},
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user