This commit is contained in:
eric
2026-03-26 11:39:56 -05:00
parent f5068c0ead
commit 11ea8d402c

View File

@@ -16,6 +16,30 @@ type PayjsVipResult = {
}; };
const inflightUserChecks = new Map<string, Promise<PayjsVipResult | null>>(); const inflightUserChecks = new Map<string, Promise<PayjsVipResult | null>>();
const inflightUserRequests = new Map<
string,
Promise<{
ok: true;
vip: boolean;
alreadyLinked: boolean;
email?: string;
linkedUserId?: string;
}>
>();
const userCheckResultCache = new Map<
string,
{
expiresAt: number;
payload: {
ok: true;
vip: boolean;
alreadyLinked: boolean;
email?: string;
linkedUserId?: string;
};
}
>();
const USER_CHECK_CACHE_TTL_MS = Number(process.env.CHECK_BY_USER_CACHE_TTL_MS) || 10_000;
async function fetchPayjsVipWithRetry( async function fetchPayjsVipWithRetry(
url: string, url: string,
@@ -126,6 +150,21 @@ export async function POST(request: NextRequest) {
); );
} }
const cached = userCheckResultCache.get(userId);
if (cached && cached.expiresAt > Date.now()) {
return NextResponse.json(cached.payload);
}
if (cached) {
userCheckResultCache.delete(userId);
}
const inflight = inflightUserRequests.get(userId);
if (inflight) {
const payload = await inflight;
return NextResponse.json(payload);
}
const task = (async () => {
let payjsResult: PayjsVipResult | null = null; let payjsResult: PayjsVipResult | null = null;
let vip = false; let vip = false;
let email: string | null = null; let email: string | null = null;
@@ -144,12 +183,12 @@ export async function POST(request: NextRequest) {
vip = !!payjsResult?.vip; vip = !!payjsResult?.vip;
email = payjsResult?.email ?? null; email = payjsResult?.email ?? null;
console.error("[check-by-user] missing PocketBase admin token, fallback to payjs result"); console.error("[check-by-user] missing PocketBase admin token, fallback to payjs result");
return NextResponse.json({ return {
ok: true, ok: true,
vip, vip,
alreadyLinked: !!email, alreadyLinked: !!email,
email: email ?? undefined, email: email ?? undefined,
}); };
} }
if (!vip) { if (!vip) {
@@ -249,16 +288,29 @@ export async function POST(request: NextRequest) {
linkedUserId || "(none)" linkedUserId || "(none)"
); );
return NextResponse.json({ return {
ok: true, ok: true,
vip, vip,
alreadyLinked: !!email, alreadyLinked: !!email,
email: email ?? undefined, email: email ?? undefined,
linkedUserId, linkedUserId,
}); };
} catch (error) { } catch (error) {
console.error("[check-by-user] failed:", error); console.error("[check-by-user] failed:", error);
// 接口容错:即使 PB 回退失败,也不抛 500 给前端 // 接口容错:即使 PB 回退失败,也不抛 500 给前端
return NextResponse.json({ ok: true, vip: false, error: "check_failed_degraded" }); return { ok: true, vip: false, alreadyLinked: false };
}
})();
inflightUserRequests.set(userId, task);
try {
const payload = await task;
userCheckResultCache.set(userId, {
payload,
expiresAt: Date.now() + USER_CHECK_CACHE_TTL_MS,
});
return NextResponse.json(payload);
} finally {
inflightUserRequests.delete(userId);
} }
} }