68 lines
2.1 KiB
TypeScript
68 lines
2.1 KiB
TypeScript
const neteaseEnhancedApiPromise = import(/* @vite-ignore */ '@neteasecloudmusicapienhanced/api').then((mod) => {
|
|
return (mod.default || {}) as Record<string, (params: Record<string, any>) => Promise<any>>
|
|
})
|
|
|
|
const normalizeParams = (input: Record<string, any>) => {
|
|
const output: Record<string, any> = {}
|
|
for (const [key, value] of Object.entries(input || {})) {
|
|
if (value === undefined || value === null || value === '') {
|
|
continue
|
|
}
|
|
output[key] = Array.isArray(value) ? value[value.length - 1] : value
|
|
}
|
|
return output
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const rawPath = getRouterParam(event, 'path')
|
|
const endpointPath = Array.isArray(rawPath) ? rawPath.join('/') : rawPath
|
|
|
|
if (!endpointPath) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: '缺少网易云接口路径'
|
|
})
|
|
}
|
|
|
|
const action = endpointPath.replace(/\//g, '_').replace(/-/g, '_')
|
|
const api = await neteaseEnhancedApiPromise
|
|
const handler = api[action]
|
|
|
|
if (typeof handler !== 'function') {
|
|
throw createError({
|
|
statusCode: 404,
|
|
message: `未找到接口: ${endpointPath}`
|
|
})
|
|
}
|
|
|
|
const method = getMethod(event)
|
|
const queryParams = normalizeParams(getQuery(event))
|
|
let bodyParams: Record<string, any> = {}
|
|
|
|
if (method !== 'GET') {
|
|
const body = await readBody(event).catch(() => ({}))
|
|
if (body && typeof body === 'object' && !Array.isArray(body)) {
|
|
bodyParams = normalizeParams(body as Record<string, any>)
|
|
}
|
|
}
|
|
|
|
const params = { ...queryParams, ...bodyParams }
|
|
|
|
try {
|
|
const result = await handler(params)
|
|
if (Array.isArray(result?.cookie) && result.cookie.length > 0) {
|
|
setHeader(event, 'set-cookie', result.cookie)
|
|
}
|
|
if (typeof result?.status === 'number') {
|
|
setResponseStatus(event, result.status)
|
|
}
|
|
return result?.body ?? result
|
|
} catch (error: any) {
|
|
throw createError({
|
|
statusCode: error?.statusCode || error?.status || 500,
|
|
message: error?.body?.message || error?.message || '网易云接口调用失败',
|
|
data: error?.body || null
|
|
})
|
|
}
|
|
})
|