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
Provenance
- Commit
d112283- Tree
692ba8c- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
17ca389
5 files changed+72 added−0 removed
modified:source/core/constants.ts+3 added
48 unmodified lines495051525354555657585939 unmodified lines48 unmodified lines text: 'text/*', formData: 'multipart/form-data', arrayBuffer: '*/*', blob: '*/*', // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici). // We still feature-check at runtime before exposing the shortcut. bytes: '*/*',} as const;
// The maximum value of a 32bit int (see issue #117)export const maxSafeTimeout = 2_147_483_647;39 unmodified linesmodified:source/core/Ky.ts+8 added
91 unmodified lines92 }93 }) as ResponsePromise;94 95 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+ }103+104 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 linesmodified:source/types/ResponsePromise.ts+7 added
8 unmodified lines9101112131415161718192021222325 unmodified lines8 unmodified lines blob: () => Promise<Blob>;
formData: () => Promise<FormData>;
/** Get the response body as raw bytes.
Note: This shortcut is only available when the runtime supports `Response.prototype.bytes()`. */ bytes: () => Promise<Uint8Array>;
// TODO: Use `json<T extends JSONValue>(): Promise<T>;` when it's fixed in TS. // See https://github.com/microsoft/TypeScript/issues/15300 and https://github.com/sindresorhus/ky/pull/80 /** Get the response body as JSON.25 unmodified linesadded:test/bytes.ts+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import {Buffer} from 'node:buffer';import test from 'ava';import ky from '../source/index.js';import {createHttpTestServer} from './helpers/create-http-test-server.js';
const supportsBytes = typeof (globalThis.Response?.prototype as unknown as {bytes?: unknown})?.bytes === 'function';
test('.bytes() returns Uint8Array when supported', async t => { const server = await createHttpTestServer();
server.get('/', (request, response) => { t.is(request.headers.accept, '*/*'); // Send raw binary bytes response.end(Buffer.from([0, 1, 2, 255])); });
if (!supportsBytes) { await ky(server.url).text(); await server.close(); t.pass(); return; }
const bytes = await ky(server.url).bytes(); t.true(bytes instanceof Uint8Array); t.deepEqual([...bytes], [0, 1, 2, 255]);
await server.close();});
test('.bytes() throws on HTTP errors when supported', async t => { const server = await createHttpTestServer();
server.get('/', (_request, response) => { response.status(400).end('nope'); });
if (!supportsBytes) { await ky(server.url, {throwHttpErrors: false}).text(); await server.close(); t.pass(); return; }
await t.throwsAsync(ky(server.url).bytes(), {message: /Bad Request/});
await server.close();});modified:readme.md+6 added
88 unmodified lines89 The `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).90 91 Returns 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.92 93+Available body shortcuts: `.json()`, `.text()`, `.formData()`, `.arrayBuffer()`, `.blob()`, and `.bytes()`. The `.bytes()` shortcut is only present when the runtime supports `Response.prototype.bytes()`.94+95 ```js96 import ky from 'ky';97 98 const user = await ky('/api/user').json();13 unmodified lines112 // user3 is a User113 const user3 = await ky('/api/users/3').json<User>();114 115 console.log([user1, user2, user3]);116+117+// Get raw bytes (when supported by the runtime)118+const bytes = await ky('/api/file').bytes();119+console.log(bytes instanceof Uint8Array);120 ```121 122 ### ky.get(input, options?)123 ### ky.post(input, options?)656 unmodified lines