Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
// src/routes/api/bandwidth/+server.ts | |
import { json } from '@sveltejs/kit'; | |
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb'; | |
import { randomUUID } from 'crypto'; | |
const REGION = process.env.AWS_REGION || 'us-east-1'; // Fallback region if none is set | |
const TABLE_NAME = process.env.DYNAMODB_TABLE; | |
if (!TABLE_NAME) { | |
console.error( | |
'DYNAMODB_TABLE environment variable is not set. Please set DYNAMODB_TABLE to your DynamoDB table name.' | |
); | |
} | |
const ddbClient = new DynamoDBClient({ region: REGION }); | |
export async function POST({ request }) { | |
try { | |
const { bandwidth, latency, location, progress } = await request.json(); | |
if ( | |
typeof bandwidth !== 'number' || | |
typeof latency !== 'number' || | |
typeof location !== 'string' || | |
typeof progress !== 'number' | |
) { | |
return json({ error: 'Invalid data' }, { status: 400 }); | |
} | |
if (!TABLE_NAME) { | |
return json({ error: 'failed to save measurements' }, { status: 500 }); | |
} | |
const item = { | |
id: { S: randomUUID() }, // primary key | |
bandwidth: { N: bandwidth.toString() }, | |
latency: { N: latency.toString() }, | |
location: { S: location }, | |
timestamp: { S: new Date().toISOString() }, | |
progress: { N: progress.toString() } | |
}; | |
const putParams = { | |
TableName: TABLE_NAME, | |
Item: item | |
}; | |
await ddbClient.send(new PutItemCommand(putParams)); | |
//console.log('Received bandwidth data:', { bandwidth, latency, location, progress }); | |
return json({ success: true }); | |
} catch (error) { | |
console.error('Error processing bandwidth data:', error); | |
return json({ error: 'Unable to process the request' }, { status: 500 }); | |
} | |
} | |