perf(oauth): Redis-cache getTokenCustomer to eliminate uncached DB hit on every ChatGPT API call
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import crypto from 'crypto';
|
||||
import type { RowDataPacket } from 'mysql2/promise';
|
||||
import { getPool, isPoolReady } from './db.js';
|
||||
import redis from './redis.js';
|
||||
|
||||
const AUTH_CODE_EXPIRY_MS = 10 * 60 * 1000; // 10 minutes
|
||||
const TOKEN_EXPIRY_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
@@ -298,13 +299,19 @@ export async function validateAccessToken(tokenValue: string): Promise<boolean>
|
||||
|
||||
export async function getTokenCustomer(tokenValue: string): Promise<{ customerId: string } | null> {
|
||||
try {
|
||||
const cacheKey = `oauth:token:${tokenValue}`;
|
||||
const cached = await redis.get(cacheKey);
|
||||
if (cached) return { customerId: cached };
|
||||
|
||||
const pool = getPool();
|
||||
const [rows] = await pool.execute<RowDataPacket[]>(
|
||||
'SELECT customer_id FROM oauth_tokens WHERE token = ? AND expires_at > NOW()',
|
||||
[tokenValue]
|
||||
);
|
||||
if (!Array.isArray(rows) || rows.length === 0 || !rows[0].customer_id) return null;
|
||||
return { customerId: rows[0].customer_id as string };
|
||||
const customerId = rows[0].customer_id as string;
|
||||
await redis.setEx(cacheKey, 60, customerId);
|
||||
return { customerId };
|
||||
} catch (err) {
|
||||
console.error('[oauth] getTokenCustomer error:', err);
|
||||
return null;
|
||||
|
||||
Reference in New Issue
Block a user