Skip to content
Myr

Add `.bytes()` shortcut (#720)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by GitHub · parent 17ca389 · Browse files · 5 files+72 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+72 added−0 removed

  • tests:+48 added−0 removed
  • other:+24 added−0 removed

5 files+72 added−0 removed

modified:source/core/constants.ts+3 added
modified:source/core/Ky.ts+8 added
91 unmodified lines
92 }93 }) as ResponsePromise;9495 for (const [type, mimeType] of Object.entries(responseTypes) as ObjectEntries<typeof responseTypes>) {96 // Only expose `.bytes()` when the environment implements it.97 if (98 type === 'bytes'99 && typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes !== 'function'100 ) {101 continue;102 }103104 result[type] = async () => {105 // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing106 ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);107
232 unmodified lines
modified:source/types/ResponsePromise.ts+7 added
added:test/bytes.ts+48 added
modified:readme.md+6 added
88 unmodified lines
89The `input` and `options` are the same as [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), with additional `options` available (see below).9091Returns a [`Response` object](https://developer.mozilla.org/en-US/docs/Web/API/Response) with [`Body` methods](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#body) added for convenience. So you can, for example, call `ky.get(input).json()` directly without having to await the `Response` first. When called like that, an appropriate `Accept` header will be set depending on the body method used. Unlike the `Body` methods of `window.Fetch`, these will throw an `HTTPError` if the response status is not in the range of `200...299`. Also, `.json()` will return an empty string if body is empty or the response status is `204` instead of throwing a parse error due to an empty body.9293Available body shortcuts: `.json()`, `.text()`, `.formData()`, `.arrayBuffer()`, `.blob()`, and `.bytes()`. The `.bytes()` shortcut is only present when the runtime supports `Response.prototype.bytes()`.9495```js96import ky from 'ky';9798const user = await ky('/api/user').json();
13 unmodified lines
112// user3 is a User113const user3 = await ky('/api/users/3').json<User>();114115console.log([user1, user2, user3]);116117// Get raw bytes (when supported by the runtime)118const bytes = await ky('/api/file').bytes();119console.log(bytes instanceof Uint8Array);120```121122### ky.get(input, options?)123### ky.post(input, options?)
656 unmodified lines