(method, options, callback)
| 12 | |
| 13 | // Helper to mimic request's callback API for get, put, post, head, patch |
| 14 | function fetchRequest (method, options, callback) { |
| 15 | // options: { url, headers, body, ... } |
| 16 | const fetchOptions = { |
| 17 | method: method.toUpperCase(), |
| 18 | headers: options.headers || {}, |
| 19 | body: options.body |
| 20 | } |
| 21 | // For GET/HEAD, don't send body |
| 22 | if (['GET', 'HEAD'].includes(fetchOptions.method)) { |
| 23 | delete fetchOptions.body |
| 24 | } |
| 25 | fetch(options.url, fetchOptions) |
| 26 | .then(async res => { |
| 27 | let body = await res.text() |
| 28 | // Try to parse as JSON if content-type is json |
| 29 | if (res.headers.get('content-type') && res.headers.get('content-type').includes('json')) { |
| 30 | try { body = JSON.parse(body) } catch (e) {} |
| 31 | } |
| 32 | callback(null, { |
| 33 | statusCode: res.status, |
| 34 | headers: Object.fromEntries(res.headers.entries()), |
| 35 | body: body, |
| 36 | statusMessage: res.statusText |
| 37 | }, body) |
| 38 | }) |
| 39 | .catch(err => callback(err)) |
| 40 | } |
| 41 | |
| 42 | function request (options, cb) { |
| 43 | // Allow string URL |
no test coverage detected