bare-fetch
Advanced tools
Comparing version 2.0.0 to 2.1.0
@@ -1,74 +0,20 @@ | ||
const { ReadableStream } = require('bare-stream/web') | ||
const Body = require('./body') | ||
const Headers = require('./headers') | ||
const errors = require('./errors') | ||
module.exports = class Response { | ||
// https://fetch.spec.whatwg.org/#response-class | ||
module.exports = class Response extends Body { | ||
constructor(body = null, opts = {}) { | ||
const { headers = new Headers(), status = 200 } = opts | ||
super(body) | ||
this.headers = headers | ||
this.status = status | ||
this.redirected = false | ||
this.body = null | ||
this.bodyUsed = false | ||
if (typeof body === 'string') body = Buffer.from(body) | ||
if (Buffer.isBuffer(body)) { | ||
this.body = new ReadableStream({ | ||
start(controller) { | ||
controller.enqueue(body) | ||
controller.close() | ||
} | ||
}) | ||
} else if (body !== null) { | ||
this.body = body | ||
} | ||
} | ||
async buffer() { | ||
if (this.bodyUsed) { | ||
throw errors.BODY_ALREADY_CONSUMED('Body has already been consumed') | ||
} | ||
this.bodyUsed = true | ||
const chunks = [] | ||
let length = 0 | ||
for await (const chunk of this.body) { | ||
chunks.push(chunk) | ||
length += chunk.byteLength | ||
} | ||
const result = Buffer.from(new ArrayBuffer(length)) | ||
let offset = 0 | ||
for (const chunk of chunks) { | ||
result.set(chunk, offset) | ||
offset += chunk.byteLength | ||
} | ||
return result | ||
// https://fetch.spec.whatwg.org/#dom-response-ok | ||
get ok() { | ||
return this.status >= 200 && this.status <= 299 | ||
} | ||
// https://fetch.spec.whatwg.org/#dom-body-bytes | ||
async bytes() { | ||
return this.buffer() | ||
} | ||
// https://fetch.spec.whatwg.org/#dom-body-arraybuffer | ||
async arrayBuffer() { | ||
return (await this.buffer()).buffer | ||
} | ||
// https://fetch.spec.whatwg.org/#dom-body-text | ||
async text() { | ||
return (await this.buffer()).toString('utf8') | ||
} | ||
// https://fetch.spec.whatwg.org/#dom-body-json | ||
async json() { | ||
return JSON.parse(await this.text()) | ||
} | ||
} |
{ | ||
"name": "bare-fetch", | ||
"version": "2.0.0", | ||
"description": "Minimal WHATWG Fetch implementation for Bare", | ||
"version": "2.1.0", | ||
"description": "WHATWG Fetch implementation for Bare", | ||
"exports": { | ||
@@ -10,2 +10,3 @@ ".": "./index.js", | ||
"./errors": "./lib/errors.js", | ||
"./body": "./lib/body.js", | ||
"./response": "./lib/response.js", | ||
@@ -12,0 +13,0 @@ "./headers": "./lib/headers.js" |
# bare-fetch | ||
Minimal WHATWG Fetch implementation for Bare. | ||
WHATWG Fetch implementation for Bare. | ||
@@ -5,0 +5,0 @@ ``` |
19140
9
189