|
| 1 | +const { serveNcmApi } = require('../../server') |
| 2 | + |
| 3 | +// 默认配置 |
| 4 | +const defaultEnv = { |
| 5 | + ENABLE_GENERAL_UNBLOCK: 'true', |
| 6 | + ENABLE_FLAC: 'true', |
| 7 | + SELECT_MAX_BR: 'true', |
| 8 | + UNBLOCK_SOURCE: 'pyncmd,qq,kuwo,migu,kugou', |
| 9 | + FOLLOW_SOURCE_ORDER: 'true', |
| 10 | + CORS_ALLOW_ORIGIN: '*', |
| 11 | + ENABLE_PROXY: 'false', |
| 12 | + PROXY_URL: '', |
| 13 | + NETEASE_COOKIE: '', |
| 14 | + JOOX_COOKIE: '', |
| 15 | + MIGU_COOKIE: '', |
| 16 | + QQ_COOKIE: '', |
| 17 | + YOUTUBE_KEY: '' |
| 18 | +} |
| 19 | + |
| 20 | +let app = null |
| 21 | + |
| 22 | +export async function onRequest(context) { |
| 23 | + const { request, env } = context |
| 24 | + |
| 25 | + // 合并默认配置和环境变量 |
| 26 | + Object.keys(defaultEnv).forEach(key => { |
| 27 | + process.env[key] = env[key] || defaultEnv[key] |
| 28 | + }) |
| 29 | + |
| 30 | + if (!app) { |
| 31 | + app = await serveNcmApi({ |
| 32 | + checkVersion: false // 禁用版本检查,避免在边缘函数环境中发起不必要的网络请求 |
| 33 | + }) |
| 34 | + } |
| 35 | + |
| 36 | + return new Promise((resolve) => { |
| 37 | + let body = [] |
| 38 | + request.arrayBuffer().then(buffer => { |
| 39 | + if (buffer.byteLength > 0) { |
| 40 | + body = Buffer.from(buffer) |
| 41 | + } |
| 42 | + |
| 43 | + // 构造 Express 兼容的请求对象 |
| 44 | + const req = new Proxy(request, { |
| 45 | + get: (target, prop) => { |
| 46 | + switch(prop) { |
| 47 | + case 'body': |
| 48 | + return body |
| 49 | + case 'query': |
| 50 | + return Object.fromEntries(new URL(request.url).searchParams) |
| 51 | + case 'cookies': |
| 52 | + return Object.fromEntries( |
| 53 | + request.headers.get('cookie')?.split(';') |
| 54 | + .map(cookie => cookie.trim().split('=')) |
| 55 | + .map(([key, value]) => [key, decodeURIComponent(value)]) || [] |
| 56 | + ) |
| 57 | + default: |
| 58 | + return target[prop] |
| 59 | + } |
| 60 | + } |
| 61 | + }) |
| 62 | + |
| 63 | + // 构造 Express 兼容的响应对象 |
| 64 | + const res = { |
| 65 | + status: (code) => { |
| 66 | + res.statusCode = code |
| 67 | + return res |
| 68 | + }, |
| 69 | + set: (headers) => { |
| 70 | + Object.entries(headers).forEach(([key, value]) => { |
| 71 | + res.headers[key] = value |
| 72 | + }) |
| 73 | + return res |
| 74 | + }, |
| 75 | + send: (body) => { |
| 76 | + const response = new Response( |
| 77 | + typeof body === 'string' ? body : JSON.stringify(body), |
| 78 | + { |
| 79 | + status: res.statusCode || 200, |
| 80 | + headers: { |
| 81 | + 'Content-Type': 'application/json;charset=utf-8', |
| 82 | + ...res.headers |
| 83 | + } |
| 84 | + } |
| 85 | + ) |
| 86 | + resolve(response) |
| 87 | + }, |
| 88 | + statusCode: 200, |
| 89 | + headers: {} |
| 90 | + } |
| 91 | + |
| 92 | + // 处理请求 |
| 93 | + app.handle(req, res) |
| 94 | + }) |
| 95 | + }) |
| 96 | +} |
0 commit comments