UNPKG

alcaeus

Version:

Hydra Core hypermedia-aware client library

57 lines (56 loc) 1.61 kB
import buffer from 'buffer'; import stream from 'readable-stream'; // from https://github.com/bergos/nodeify-fetch/blob/master/lib/WhatwgReadable.js class WhatwgReadable extends stream.Readable { constructor(body) { let reader; function getReader() { if (!reader) { reader = body.getReader(); } return reader; } super({ read: () => { getReader().read().then((chunk) => { if (chunk.done) { this.push(null); } else { this.push(buffer.Buffer.from(chunk.value)); } }).catch((err) => { this.emit('error', err); }); }, }); } } class ArrayBufferReadable extends stream.Readable { constructor(callback) { let done = false; super({ read: () => { if (done) { return; } done = true; callback().then((arrayBuffer) => { this.push(buffer.Buffer.from(arrayBuffer)); this.push(null); }); }, }); } } export function patchResponseBody(body) { if (body.body && 'readable' in body.body) { return body.body; } if (body.body && 'getReader' in body.body) { return new WhatwgReadable(body.body); } return new ArrayBufferReadable(() => { return body.arrayBuffer(); }); }