import { DynamoDBDocumentClient, GetCommand, PutCommand } from '@aws-sdk/lib-dynamodb'; import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; const region = process.env.AWS_REGION!; const tableName = process.env.RATE_LIMIT_TABLE_NAME!; const ddb = new DynamoDBClient({ region }); const doc = DynamoDBDocumentClient.from(ddb); export async function checkAndConsumeToken(userId: string, capacityPerMinute: number = 10): Promise { const now = Date.now(); const key = { userId }; const resp = await doc.send(new GetCommand({ TableName: tableName, Key: key })); const item = resp.Item || { userId, tokens: capacityPerMinute, refillAt: now }; let tokens: number = typeof item.tokens === 'number' ? item.tokens : capacityPerMinute; let refillAt: number = typeof item.refillAt === 'number' ? item.refillAt : now; if (now >= refillAt + 60_000) { tokens = capacityPerMinute; refillAt = now; } if (tokens <= 0) { return false; } tokens -= 1; await doc.send(new PutCommand({ TableName: tableName, Item: { userId, tokens, refillAt } })); return true; }