63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import {
|
|
getApiKeyFromRequest,
|
|
getClientIp,
|
|
logApiCall,
|
|
successResponse,
|
|
validateApiKey,
|
|
} from '@/lib/external-api'
|
|
import { ExternalMaterialImportError, getExternalMaterialImportSchema } from '@/lib/external-material-import'
|
|
|
|
function buildErrorResponse(status: number, code: string, message: string) {
|
|
return NextResponse.json(
|
|
{
|
|
success: false,
|
|
error: {
|
|
code,
|
|
message,
|
|
},
|
|
},
|
|
{ status },
|
|
)
|
|
}
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const startTime = Date.now()
|
|
const apiKey = getApiKeyFromRequest(request)
|
|
const keyRecord = await validateApiKey(apiKey)
|
|
|
|
if (!keyRecord) {
|
|
return buildErrorResponse(401, 'INVALID_API_KEY', 'API Key 无效或缺失')
|
|
}
|
|
|
|
const materialType = request.nextUrl.searchParams.get('materialType') || ''
|
|
|
|
try {
|
|
const data = await getExternalMaterialImportSchema(materialType)
|
|
await logApiCall({
|
|
apiKeyId: keyRecord.id,
|
|
endpoint: '/api/external/material-import/schema',
|
|
method: 'GET',
|
|
statusCode: 200,
|
|
duration: Date.now() - startTime,
|
|
ipAddress: getClientIp(request),
|
|
userAgent: request.headers.get('user-agent') || undefined,
|
|
})
|
|
return successResponse(data)
|
|
} catch (error) {
|
|
const status = error instanceof ExternalMaterialImportError ? error.status : 500
|
|
const code = error instanceof ExternalMaterialImportError ? error.code : 'SERVER_ERROR'
|
|
const message = error instanceof Error ? error.message : '服务器内部错误'
|
|
await logApiCall({
|
|
apiKeyId: keyRecord.id,
|
|
endpoint: '/api/external/material-import/schema',
|
|
method: 'GET',
|
|
statusCode: status,
|
|
duration: Date.now() - startTime,
|
|
ipAddress: getClientIp(request),
|
|
userAgent: request.headers.get('user-agent') || undefined,
|
|
})
|
|
return buildErrorResponse(status, code, message)
|
|
}
|
|
}
|