File size: 1,984 Bytes
9580dce | 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 66 67 68 69 70 71 72 73 | import { NextResponse } from "next/server";
import { withApiError } from "@/lib/api-error";
import { ApiError } from "@/lib/api-error";
import { getPerformanceSummary } from "@/lib/performance";
import {
generateCoachFeedback,
isRateLimited,
recordRequest,
} from "@/lib/coach-feedback";
/**
* POST /api/coach/feedback
*
* Returns Claude-generated personalized coaching feedback based on the
* user's performance data and difficulty recommendations.
*
* Request body (optional):
* { "userId": number } — defaults to 1
*
* Response shape:
* {
* feedback: string,
* recommendedExercise: { category: string, difficulty: string },
* encouragement: string,
* cached: boolean
* }
*
* Features:
* - 3-hour response cache (keyed on user ID + rounded performance metrics)
* - Rate limit: max 10 requests per user per hour
*
* Part 3 of the Active Coach roadmap (Issue #7).
*/
export const POST = withApiError(async (request) => {
if (!process.env.ANTHROPIC_API_KEY) {
return NextResponse.json(
{ error: "ANTHROPIC_API_KEY is not configured" },
{ status: 503 },
);
}
// Parse optional body
let userId = 1;
try {
const body = await request.json();
if (body.userId && typeof body.userId === "number") {
userId = body.userId;
}
} catch {
// Empty body is fine — default to user 1
}
// Rate limit check
if (isRateLimited(userId)) {
throw new ApiError(429, "Rate limit exceeded — max 10 requests per hour");
}
// Get performance summary
const summary = await getPerformanceSummary(userId);
// Generate feedback (may return cached response)
const { feedback, cached } = await generateCoachFeedback(userId, summary);
// Record the request for rate limiting (only count non-cached responses,
// but count all for simplicity — cached responses are fast anyway)
recordRequest(userId);
return NextResponse.json({
...feedback,
cached,
});
});
|