(method, url, body, opts = {})
| 64 | const UA = 'web-check/1.0 (https://web-check.xyz)'; |
| 65 | |
| 66 | const send = async (method, url, body, opts = {}) => { |
| 67 | const finalUrl = appendParams(url, opts.params); |
| 68 | const headers = { 'user-agent': UA, ...opts.headers }; |
| 69 | const authHeader = buildAuth(opts.auth); |
| 70 | if (authHeader) headers.authorization = authHeader; |
| 71 | |
| 72 | const init = { |
| 73 | method, |
| 74 | headers, |
| 75 | signal: AbortSignal.timeout(opts.timeout || DEFAULT_TIMEOUT), |
| 76 | }; |
| 77 | |
| 78 | if (body !== undefined && body !== null) { |
| 79 | if (typeof body === 'object') { |
| 80 | init.body = JSON.stringify(body); |
| 81 | const hasCt = Object.keys(headers).some((k) => k.toLowerCase() === 'content-type'); |
| 82 | if (!hasCt) init.headers['content-type'] = 'application/json'; |
| 83 | } else { |
| 84 | init.body = body; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | let response; |
| 89 | try { |
| 90 | response = await fetch(finalUrl, init); |
| 91 | } catch (error) { |
| 92 | throw wrapNetworkError(error); |
| 93 | } |
| 94 | |
| 95 | const data = await parseBody(response); |
| 96 | const result = { |
| 97 | data, |
| 98 | status: response.status, |
| 99 | statusText: response.statusText, |
| 100 | headers: headersToObject(response.headers), |
| 101 | }; |
| 102 | |
| 103 | if (!isOk(response.status, opts.validateStatus)) { |
| 104 | const err = new Error(`Request failed with status code ${response.status}`); |
| 105 | err.response = result; |
| 106 | throw err; |
| 107 | } |
| 108 | |
| 109 | return result; |
| 110 | }; |
| 111 | |
| 112 | export const httpGet = (url, opts) => send('GET', url, null, opts); |
| 113 | export const httpPost = (url, body, opts) => send('POST', url, body, opts); |
no test coverage detected