67 lines
1.9 KiB
TypeScript
67 lines
1.9 KiB
TypeScript
import type { MongoClient } from 'mongodb'
|
|
import { connectToDatabase, fetchLatestPatch } from '../../utils/mongo'
|
|
|
|
async function championInfos(client: MongoClient, patch: string, championAlias: string) {
|
|
const database = client.db('champions')
|
|
const collection = database.collection(patch)
|
|
const query = { alias: championAlias }
|
|
const championInfo = (await collection.findOne(query)) as unknown as ChampionData | null
|
|
return championInfo
|
|
}
|
|
|
|
export default defineEventHandler(async event => {
|
|
try {
|
|
const championAlias = (getRouterParam(event, 'alias') as string).toLowerCase()
|
|
|
|
// Validate champion alias
|
|
if (!championAlias || typeof championAlias !== 'string') {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Invalid champion alias',
|
|
data: { alias: championAlias }
|
|
})
|
|
}
|
|
|
|
const client = await connectToDatabase()
|
|
const latestPatch = await fetchLatestPatch(client)
|
|
const data = await championInfos(client, latestPatch, championAlias)
|
|
await client.close()
|
|
|
|
if (!data) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: 'Champion not found',
|
|
data: { alias: championAlias, patch: latestPatch }
|
|
})
|
|
}
|
|
|
|
return data
|
|
} catch (error) {
|
|
console.error('Error in champion API:', error)
|
|
|
|
// Handle different error types
|
|
if (error instanceof Error) {
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Failed to fetch champion data',
|
|
data: {
|
|
error: error.message,
|
|
championAlias: getRouterParam(event, 'alias')
|
|
}
|
|
})
|
|
}
|
|
|
|
// Re-throw if it's already a proper error
|
|
if (error && typeof error === 'object' && 'statusCode' in error) {
|
|
throw error
|
|
}
|
|
|
|
// Fallback error
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Internal server error',
|
|
data: { championAlias: getRouterParam(event, 'alias') }
|
|
})
|
|
}
|
|
})
|