39 lines
1.3 KiB
JavaScript
39 lines
1.3 KiB
JavaScript
const base = () => (process.env.WHATSAPP_GATEWAY_URL || 'http://whatsapp-gateway:3200').replace(/\/$/, '')
|
|
|
|
export async function whatsappRequest(path, options = {}) {
|
|
const token = String(process.env.WHATSAPP_GATEWAY_TOKEN || '')
|
|
if (token.length < 24) {
|
|
throw Object.assign(new Error('WhatsApp 网关令牌尚未配置'), { status: 503 })
|
|
}
|
|
const response = await fetch(`${base()}${path}`, {
|
|
...options,
|
|
headers: {
|
|
...(options.body instanceof FormData ? {} : { 'content-type': 'application/json' }),
|
|
authorization: `Bearer ${token}`,
|
|
...(options.headers || {}),
|
|
},
|
|
})
|
|
const raw = await response.text()
|
|
let result
|
|
try { result = raw ? JSON.parse(raw) : null } catch { result = raw }
|
|
if (!response.ok) {
|
|
throw Object.assign(
|
|
new Error(result?.message || `WhatsApp 网关请求失败 (${response.status})`),
|
|
{ status: response.status, data: result?.data },
|
|
)
|
|
}
|
|
return result?.data ?? result
|
|
}
|
|
|
|
export function postWhatsApp(path, body) {
|
|
return whatsappRequest(path, { method: 'POST', body: JSON.stringify(body) })
|
|
}
|
|
|
|
export function putWhatsApp(path, body) {
|
|
return whatsappRequest(path, { method: 'PUT', body: JSON.stringify(body) })
|
|
}
|
|
|
|
export function uploadWhatsApp(path, formData) {
|
|
return whatsappRequest(path, { method: 'POST', body: formData })
|
|
}
|