Files
Jyotisha/frontend/src/app/api/redeem/route.ts
T
Jesse_ChenandCursor 31b54aa71d
Independent Staging Quality Gate / validate (push) Successful in 9m34s
Independent Staging Quality Gate / publish (push) Successful in 7m21s
fix(frontend): say the database is missing, not Supabase
Self-hosted PostgreSQL is the runtime. A missing APP_DATABASE_URL
must not tell users the retired hosted service is unconfigured.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-29 09:44:53 +08:00

89 lines
2.7 KiB
TypeScript

import { NextResponse } from "next/server";
import { z } from "zod";
import { hashRedeemCode } from "@/lib/supabase/codes";
import { isSupabaseConfigurationError } from "@/lib/supabase/config";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import {
redeemErrorResponse,
redeemInputErrorResponse,
} from "@/lib/redeem-response";
export const runtime = "nodejs";
const requestSchema = z.object({ code: z.string().max(100) });
export async function POST(request: Request) {
try {
const parsed = requestSchema.safeParse(
await request.json().catch(() => null),
);
if (!parsed.success) {
const inputError = redeemInputErrorResponse();
return NextResponse.json(
{ error: inputError.message, code: inputError.code },
{ status: inputError.status },
);
}
// Only surrounding whitespace is trimmed; case is never changed. Every
// non-empty value is hashed as-is and evaluated by the database, so
// lowercase or malformed attempts still hit the RPC failure rate limit
// instead of being short-circuited client-side.
const code = parsed.data.code.trim();
if (!code) {
const inputError = redeemInputErrorResponse();
return NextResponse.json(
{ error: inputError.message, code: inputError.code },
{ status: inputError.status },
);
}
const supabase = await createServerSupabaseClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json({ error: "请先登录" }, { status: 401 });
}
const { data, error } = await supabase.rpc("redeem_code", {
p_code_hash: hashRedeemCode(code),
});
if (error) {
const systemError = redeemErrorResponse("system_error");
return NextResponse.json(
{ error: systemError.message, code: systemError.code },
{ status: systemError.status },
);
}
const result = Array.isArray(data) ? data[0] : data;
if (!result?.success) {
const mapped = redeemErrorResponse(result?.error_code);
return NextResponse.json(
{ error: mapped.message, code: mapped.code },
{ status: mapped.status },
);
}
return NextResponse.json({
awardedCredits: result.awarded_credits ?? null,
credits: result.credits,
});
} catch (error) {
if (isSupabaseConfigurationError(error)) {
return NextResponse.json(
{ error: "数据库尚未配置", code: "DATABASE_NOT_CONFIGURED" },
{ status: 503 },
);
}
const systemError = redeemErrorResponse("system_error");
return NextResponse.json(
{ error: systemError.message, code: systemError.code },
{ status: systemError.status },
);
}
}