'
This commit is contained in:
@@ -16,6 +16,30 @@ type PayjsVipResult = {
|
||||
};
|
||||
|
||||
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(
|
||||
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 vip = false;
|
||||
let email: string | null = null;
|
||||
@@ -144,12 +183,12 @@ export async function POST(request: NextRequest) {
|
||||
vip = !!payjsResult?.vip;
|
||||
email = payjsResult?.email ?? null;
|
||||
console.error("[check-by-user] missing PocketBase admin token, fallback to payjs result");
|
||||
return NextResponse.json({
|
||||
return {
|
||||
ok: true,
|
||||
vip,
|
||||
alreadyLinked: !!email,
|
||||
email: email ?? undefined,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
if (!vip) {
|
||||
@@ -249,16 +288,29 @@ export async function POST(request: NextRequest) {
|
||||
linkedUserId || "(none)"
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
return {
|
||||
ok: true,
|
||||
vip,
|
||||
alreadyLinked: !!email,
|
||||
email: email ?? undefined,
|
||||
linkedUserId,
|
||||
});
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("[check-by-user] failed:", error);
|
||||
// 接口容错:即使 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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user