(method, path, { baseUrl, apiKey, params, jsonData, timeout = 30000 } = {})
| 1988 | } |
| 1989 | |
| 1990 | async function requestLuckmail(method, path, { baseUrl, apiKey, params, jsonData, timeout = 30000 } = {}) { |
| 1991 | const requestUrl = new URL(`${normalizeLuckmailBaseUrl(baseUrl)}${path}`); |
| 1992 | if (params && typeof params === 'object') { |
| 1993 | for (const [key, value] of Object.entries(params)) { |
| 1994 | if (value === undefined || value === null || value === '') continue; |
| 1995 | requestUrl.searchParams.set(key, String(value)); |
| 1996 | } |
| 1997 | } |
| 1998 | |
| 1999 | const controller = new AbortController(); |
| 2000 | const timeoutId = setTimeout(() => controller.abort(), timeout); |
| 2001 | const headers = { |
| 2002 | Accept: 'application/json', |
| 2003 | }; |
| 2004 | if (apiKey) { |
| 2005 | headers['X-API-Key'] = apiKey; |
| 2006 | } |
| 2007 | |
| 2008 | const upperMethod = String(method || 'GET').toUpperCase(); |
| 2009 | const fetchOptions = { |
| 2010 | method: upperMethod, |
| 2011 | headers, |
| 2012 | signal: controller.signal, |
| 2013 | }; |
| 2014 | if (jsonData !== undefined) { |
| 2015 | headers['Content-Type'] = 'application/json'; |
| 2016 | fetchOptions.body = JSON.stringify(jsonData || {}); |
| 2017 | } |
| 2018 | |
| 2019 | let response = null; |
| 2020 | try { |
| 2021 | response = await fetch(requestUrl.toString(), fetchOptions); |
| 2022 | } catch (err) { |
| 2023 | if (err?.name === 'AbortError') { |
| 2024 | throw new Error(`LuckMail 请求超时:${path}`); |
| 2025 | } |
| 2026 | throw new Error(`LuckMail 请求失败:${err.message}`); |
| 2027 | } finally { |
| 2028 | clearTimeout(timeoutId); |
| 2029 | } |
| 2030 | |
| 2031 | let payload = null; |
| 2032 | try { |
| 2033 | payload = await response.json(); |
| 2034 | } catch { |
| 2035 | throw new Error(`LuckMail 返回了无法解析的响应:${path}`); |
| 2036 | } |
| 2037 | |
| 2038 | if (!response.ok) { |
| 2039 | const errorText = String(payload?.message || response.statusText || 'HTTP error'); |
| 2040 | throw new Error(`LuckMail 请求失败:${errorText}`); |
| 2041 | } |
| 2042 | |
| 2043 | if (!payload || typeof payload !== 'object') { |
| 2044 | throw new Error(`LuckMail 返回数据无效:${path}`); |
| 2045 | } |
| 2046 | |
| 2047 | if (payload.code !== 0) { |
no test coverage detected