02 api.relay(method, url, headers = {}, body = '') (1/2)
The reader makes the request and streams the answer back.
const r = await api.relay('GET', 'https://api.example.com/items?limit=10',
{ Accept: 'application/json' });
if (r.status !== 200) throw new Error('HTTP ' + r.status);
const data = JSON.parse(r.body);
// Response headers: ordered [name, value] pairs, duplicates kept
const cookies = r.headers.filter(([n]) => n.toLowerCase() === 'set-cookie').map(([, v]) => v);
- Any method. body is a string. To send JSON, use JSON.stringify(...) and set Content-Type yourself.
- r.body is a text string. Binary responses don't survive. Use fetchToSd for files.
- Response body cap: 64 KB. Over the cap (or a dropped connection) -> throws an Error with err.status === 502.
- Redirects are NOT followed. You get the 3xx and its location header and must follow it yourself:
async function relayFollow(method, url, headers, body, hops = 5) {
for (let i = 0; i <= hops; i++) {
const r = await api.relay(method, url, headers, body);
if (r.status < 300 || r.status >= 400) return r;
const loc = r.headers.find(([n]) => n.toLowerCase() === 'location');
if (!loc) return r;
url = new URL(loc[1], url).href;
if (r.status === 303) { method = 'GET'; body = ''; }
}
throw new Error('too many redirects');
}