Fix docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 16b5936 · Browse files · 6 files·+94 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+94 added−27 removed
- tests:+38 added−1 removed
- other:+56 added−26 removed
Provenance
- Commit
d4ce7b1- Tree
9f3027f- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
16b5936
6 files changed+94 added−27 removed
modified:source/core/Ky.ts+9 added-3 removed
289 unmodified lines290 let responseFromHook = beforeRequestResponse !== undefined291 || ky.#consumeReturnedResponseFromBeforeRetryHook();292 293 for (;;) {294- // `undefined` means a hook stopped the flow without providing a response.294+ // A nullish value means a hook stopped the flow, or a custom `fetch` resolved with nothing. The caller295+ // sees it normalized to `undefined` either way.296 // Non-native Responses still continue through Ky if they pass `isResponseInstance()`.296- if (response === undefined) {297+ if (response === undefined || response === null) {298 return response;299 }300 301 if (isResponseInstance(response)) {1233 unmodified lines1535 return this.#responseRequests.get(response) ?? this.request;1536 }1537 1538 #setResponseRequest(response: Response, request: Request): Response {1539+ // A custom `fetch` is allowed to resolve with anything, and the main loop decides what to do with a value that1540+ // is not a Response. A primitive cannot key a `WeakMap`, so only a real object is recorded.1541+ if (isResponseInstance(response)) {1538- this.#responseRequests.set(response, request);1542+ this.#responseRequests.set(response, request);1543+ }1544+1545 return response;1546 }1547 1548 #limitResponseSize(response: Response): Response {12 unmodified linesmodified:source/types/ky.ts+5 added-7 removed
129 unmodified lines130 @example131 ```132 import ky from 'ky';133 134- const options = {134+ // Note that response will be `undefined` in case `ky.stop` is returned.135+ const response = await ky.post('https://example.com', {136 hooks: {137 beforeRetry: [137- async ({request, options, error, retryCount}) => {138+ async ({error}) => {139 const shouldStopRetry = await ky('https://example.com/api');140 if (shouldStopRetry) {141 return ky.stop;142 }143 }144 ]145 }145- };146+ });147 147- // Note that response will be `undefined` in case `ky.stop` is returned.148- const response = await ky.post('https://example.com', options);149-148 // Using `.text()` or other body methods is not supported.151- const text = await ky('https://example.com', options).text();149+ // const text = await ky('https://example.com', options).text();150 ```151 */152 readonly stop: typeof stop;153 49 unmodified linesmodified:source/types/options.ts+21 added-3 removed
447 unmodified lines448 export interface Options extends KyOptions, RequestOptions { // eslint-disable-line @typescript-eslint/consistent-type-definitions -- This must stay an interface so that it can be extended outside of Ky for use in `ky.create`.449 /**450 HTTP method used to make the request.451 452+ Ky forwards every option it does not recognize straight to `fetch()`, so fetch-only extensions are supported even453+ when the ambient `RequestInit` type does not declare them. The two documented below are declared here for that454+ reason; any other extension is accepted at runtime and needs a type assertion.455+ */456+457+ /**458+ An undici `Agent` or `Dispatcher`, forwarded to `fetch()` as-is.459+ */460+ dispatcher?: unknown;461+462+ /**463+ A framework-specific fetch extension, such as Next.js's `next`, forwarded to `fetch()` as-is.464+ */465+ next?: unknown;466+467+ /**468+ HTTP method used to make the request.469+470 Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.471 */472 method?: LiteralUnion<HttpMethod, string> | undefined;473 22 unmodified lines496 rainbow: undefined497 }498 });499 482- const response = await extended(url).json();500+ const response = await extended(url);501 484- console.log('rainbow' in response);502+ console.log(response.headers.has('rainbow'));503 //=> false504 487- console.log('unicorn' in response);505+ console.log(response.headers.has('unicorn'));506 //=> true507 ```508 */509 headers?: KyHeadersInit | undefined;57 unmodified linesmodified:test/fetch.ts+38 added-1 removed
1 import {setTimeout as delay} from 'node:timers/promises';2 import test from 'ava';3-import ky, {NetworkError} from '../source/index.js';3+import ky, {HTTPError, NetworkError} from '../source/index.js';4 import {createHttpTestServer} from './helpers/create-http-test-server.js';5 6 const fixture = 'https://example.com/unicorn';7 902 unmodified lines910 hasOwnProperty: 'fetch-has-own-property',911 fetch: customFetch,912 } as never).text();913 });914+915+// A custom `fetch` is allowed to resolve with anything, and Ky's own comments say a non-native Response only916+// continues if it passes `isResponseInstance()`. Recording the value in a `WeakMap` first made that unreachable for917+// a primitive, and reported a message that named a `WeakMap` instead of the option that was wrong.918+test('a custom fetch that resolves with a non-Response does not crash on a WeakMap key', async t => {919+ const responseLike = {920+ status: 200,921+ ok: true,922+ type: 'default',923+ headers: new Headers(),924+ async text() {925+ return 'ok';926+ },927+ clone() {928+ return responseLike;929+ },930+ [Symbol.toStringTag]: 'Response',931+ };932+933+ // A nullish result is normalized to `undefined`, the same as a hook that stopped the flow.934+ for (const value of [undefined, null]) {935+ // eslint-disable-next-line no-await-in-loop936+ t.is(await ky(fixture, {retry: 0, fetch: async () => value as Response}), undefined);937+ }938+939+ t.is(await ky(fixture, {retry: 0, fetch: async () => responseLike as unknown as Response}), responseLike);940+});941+942+test('a custom fetch that resolves with a value that is not a response produces an HTTPError', async t => {943+ for (const value of ['ok', 42, {}] as unknown[]) {944+ // eslint-disable-next-line no-await-in-loop945+ await t.throwsAsync(ky(fixture, {retry: 0, fetch: async () => value as Response}).text(), {946+ instanceOf: HTTPError,947+ message: /an unknown error/,948+ }, `value: ${String(value)}`);949+ }950+});added:test-d/fetch-extensions.ts+9 added
123456789import type {Options} from 'ky';
// Ky forwards options it does not recognize to `fetch()`, so a fetch-only extension must be accepted even though// the ambient `RequestInit` type does not declare it.const withDispatcher: Options = {dispatcher: {fake: true}};const withNext: Options = {next: {revalidate: 0}};
void withDispatcher;void withNext;modified:readme.md+12 added-13 removed
999 unmodified lines1000 afterResponse: [ () => console.log('after 2') ],1001 }1002 });1003 1004-const response = await extended(url).json();1004+const response = await extended(url);1005 //=> after 11006 //=> after 21007 1008-console.log('rainbow' in response);1008+console.log(response.headers.has('rainbow'));1009 //=> false1010 1011-console.log('unicorn' in response);1011+console.log(response.headers.has('unicorn'));1012 //=> true1013 ```1014 1015 You can also refer to parent defaults by providing a function to `.extend()`.66 unmodified lines1082 1083 ```js1084 import ky from 'ky';1085 1086-const options = {1086+// Note that `response` will be `undefined` in case `ky.stop` is returned.1087+const response = await ky.post('https://example.com', {1088 hooks: {1089 beforeRetry: [1090 async ({request, options, error, retryCount}) => {1091 const shouldStopRetry = await ky('https://example.com/api');2 unmodified lines1094 }1095 }1096 ]1097 }1097-};1098+});1099 1099-// Note that `response` will be `undefined` in case `ky.stop` is returned.1100-const response = await ky.post('https://example.com', options);1101-1100 // Using `.text()` or other body methods is not supported.1101 const text = await ky('https://example.com', options).text();1102 ```1103 299 unmodified lines1403 ## Tips1404 1405 ### Sending form data1406 1409-Sending form data in Ky is identical to `fetch`. Just pass a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instance to the `body` option. The `Content-Type` header will be automatically set to `multipart/form-data`, overriding any existing `Content-Type` header.1407+Sending form data in Ky is identical to `fetch`. Just pass a [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) instance to the `body` option. The `Content-Type` header will be automatically set to `multipart/form-data`, unless you set a `Content-Type` in the `headers` option, which always takes precedence.1408 1409 ```js1410 import ky from 'ky';1411 4 unmodified lines1416 1417 const response = await ky.post(url, {body: formData});1418 ```1419 1422-If you want to send the data in `application/x-www-form-urlencoded` format, you will need to encode the data with [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). Like `FormData`, this will override any existing `Content-Type` headers.1420+If you want to send the data in `application/x-www-form-urlencoded` format, you will need to encode the data with [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams). Like `FormData`, the `Content-Type` is set for you unless you set one in the `headers` option.1421 1422 ```js1423 import ky from 'ky';1424 232 unmodified lines1657 interface CustomError extends HTTPError {1658 customProperty: unknown;1659 }1660 1661+// Use with type assertion1662+let data: unknown;1663+1664 const api = ky.extend({1665 hooks: {1666 beforeError: [1667 async ({error}) => {1668 if (isHTTPError(error)) {1669 (error as CustomError).customProperty = 'value';1670+ data = (error as CustomError).customProperty;1671 }1672 1673 return error;1674 }1675 ]1676 }1677 });1676-1677-// Use with type assertion1678-const data = (error as CustomError).customProperty;1678 ```1679 1680 This approach keeps your types scoped to where they're needed without polluting the global namespace.1681 227 unmodified lines