|
| 1 | +import { aggregateTokenUsage } from './repository'; |
| 2 | +import { GetTokenUsageEvent } from 'generative-ai-use-cases'; |
| 3 | + |
| 4 | +export const handler = async (event: GetTokenUsageEvent) => { |
| 5 | + try { |
| 6 | + console.log('Getting token usage statistics', { event }); |
| 7 | + |
| 8 | + // Get user ID from Cognito |
| 9 | + const userId = event.requestContext.authorizer!.claims['cognito:username']; |
| 10 | + const { startDate, endDate } = event.queryStringParameters || {}; |
| 11 | + |
| 12 | + if (!startDate || !endDate) { |
| 13 | + return { |
| 14 | + statusCode: 400, |
| 15 | + headers: { |
| 16 | + 'Content-Type': 'application/json', |
| 17 | + 'Access-Control-Allow-Origin': '*', |
| 18 | + }, |
| 19 | + body: JSON.stringify({ |
| 20 | + message: 'startDate and endDate parameters are required', |
| 21 | + }), |
| 22 | + }; |
| 23 | + } |
| 24 | + |
| 25 | + // Get aggregated data for the specified period |
| 26 | + const stats = await aggregateTokenUsage(startDate, endDate, [userId]); |
| 27 | + |
| 28 | + return { |
| 29 | + statusCode: 200, |
| 30 | + headers: { |
| 31 | + 'Content-Type': 'application/json', |
| 32 | + 'Access-Control-Allow-Origin': '*', |
| 33 | + }, |
| 34 | + body: JSON.stringify(stats), |
| 35 | + }; |
| 36 | + } catch (error) { |
| 37 | + console.error('Error getting token usage statistics:', error); |
| 38 | + return { |
| 39 | + statusCode: 500, |
| 40 | + headers: { |
| 41 | + 'Content-Type': 'application/json', |
| 42 | + 'Access-Control-Allow-Origin': '*', |
| 43 | + }, |
| 44 | + body: JSON.stringify({ |
| 45 | + message: 'Internal server error', |
| 46 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 47 | + }), |
| 48 | + }; |
| 49 | + } |
| 50 | +}; |
0 commit comments