feat: add Zod schema validation to patterns/detect route
- Import z from zod - Add CandleSchema validating time, open, high, low, close (number), volume (optional number) - Add PatternDetectRequestSchema validating candles array and patterns array of non-empty strings - Use safeParse() and return HTTP 400 with error details on validation failure - Forward only validated data to the inference service - Mark task 4.5 as completed in tasks.md Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
2e02d155af
commit
81e3554d82
2 changed files with 28 additions and 2 deletions
|
|
@ -1,9 +1,24 @@
|
|||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { z } from 'zod';
|
||||
|
||||
const INFERENCE_API_URL = process.env.INFERENCE_API_URL || 'http://localhost:8001';
|
||||
// Pattern detection may take longer on large datasets
|
||||
const INFERENCE_API_TIMEOUT = parseInt(process.env.INFERENCE_API_TIMEOUT || '60000', 10);
|
||||
|
||||
const CandleSchema = z.object({
|
||||
time: z.number(),
|
||||
open: z.number(),
|
||||
high: z.number(),
|
||||
low: z.number(),
|
||||
close: z.number(),
|
||||
volume: z.number().optional(),
|
||||
});
|
||||
|
||||
const PatternDetectRequestSchema = z.object({
|
||||
candles: z.array(CandleSchema),
|
||||
patterns: z.array(z.string().min(1)),
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), INFERENCE_API_TIMEOUT);
|
||||
|
|
@ -11,10 +26,21 @@ export async function POST(request: NextRequest) {
|
|||
try {
|
||||
const body = await request.json();
|
||||
|
||||
const result = PatternDetectRequestSchema.safeParse(body);
|
||||
if (!result.success) {
|
||||
clearTimeout(timeoutId);
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid request', details: result.error.flatten() },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const validatedBody = result.data;
|
||||
|
||||
const response = await fetch(`${INFERENCE_API_URL}/patterns/detect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-API-Key': process.env.API_KEY || '' },
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify(validatedBody),
|
||||
signal: controller.signal,
|
||||
});
|
||||
clearTimeout(timeoutId);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue