Skip to content
Myr

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

6 files+94 added−27 removed

modified:source/core/Ky.ts+9 added-3 removed
289 unmodified lines
290 let responseFromHook = beforeRequestResponse !== undefined291 || ky.#consumeReturnedResponseFromBeforeRetryHook();292293 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 }300301 if (isResponseInstance(response)) {
1233 unmodified lines
1535 return this.#responseRequests.get(response) ?? this.request;1536 }15371538 #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 }15441545 return response;1546 }15471548 #limitResponseSize(response: Response): Response {
12 unmodified lines
modified:source/types/ky.ts+5 added-7 removed
129 unmodified lines
130 @example131 ```132 import ky from 'ky';133134 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 });147147 // Note that response will be `undefined` in case `ky.stop` is returned.148 const response = await ky.post('https://example.com', options);149148 // 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 lines
modified:source/types/options.ts+21 added-3 removed
447 unmodified lines
448export 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.451452 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 */456457 /**458 An undici `Agent` or `Dispatcher`, forwarded to `fetch()` as-is.459 */460 dispatcher?: unknown;461462 /**463 A framework-specific fetch extension, such as Next.js's `next`, forwarded to `fetch()` as-is.464 */465 next?: unknown;466467 /**468 HTTP method used to make the request.469470 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 lines
496 rainbow: undefined497 }498 });499482 const response = await extended(url).json();500 const response = await extended(url);501484 console.log('rainbow' in response);502 console.log(response.headers.has('rainbow'));503 //=> false504487 console.log('unicorn' in response);505 console.log(response.headers.has('unicorn'));506 //=> true507 ```508 */509 headers?: KyHeadersInit | undefined;
57 unmodified lines
modified:test/fetch.ts+38 added-1 removed
1import {setTimeout as delay} from 'node:timers/promises';2import test from 'ava';3import ky, {NetworkError} from '../source/index.js';3import ky, {HTTPError, NetworkError} from '../source/index.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';56const fixture = 'https://example.com/unicorn';7
902 unmodified lines
910 hasOwnProperty: 'fetch-has-own-property',911 fetch: customFetch,912 } as never).text();913});914915// 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.918test('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 };932933 // 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 }938939 t.is(await ky(fixture, {retry: 0, fetch: async () => responseLike as unknown as Response}), responseLike);940});941942test('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
modified:readme.md+12 added-13 removed
999 unmodified lines
1000 afterResponse: [ () => console.log('after 2') ],1001 }1002});10031004const response = await extended(url).json();1004const response = await extended(url);1005//=> after 11006//=> after 210071008console.log('rainbow' in response);1008console.log(response.headers.has('rainbow'));1009//=> false10101011console.log('unicorn' in response);1011console.log(response.headers.has('unicorn'));1012//=> true1013```10141015You can also refer to parent defaults by providing a function to `.extend()`.
66 unmodified lines
10821083```js1084import ky from 'ky';10851086const options = {1086// Note that `response` will be `undefined` in case `ky.stop` is returned.1087const 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 lines
1094 }1095 }1096 ]1097 }1097};1098});10991099// Note that `response` will be `undefined` in case `ky.stop` is returned.1100const response = await ky.post('https://example.com', options);11011100// Using `.text()` or other body methods is not supported.1101const text = await ky('https://example.com', options).text();1102```1103
299 unmodified lines
1403## Tips14041405### Sending form data14061409Sending 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.1407Sending 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.14081409```js1410import ky from 'ky';1411
4 unmodified lines
14161417const response = await ky.post(url, {body: formData});1418```14191422If 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.1420If 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.14211422```js1423import ky from 'ky';1424
232 unmodified lines
1657interface CustomError extends HTTPError {1658 customProperty: unknown;1659}16601661// Use with type assertion1662let data: unknown;16631664const 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 }16721673 return error;1674 }1675 ]1676 }1677});16761677// Use with type assertion1678const data = (error as CustomError).customProperty;1678```16791680This approach keeps your types scoped to where they're needed without polluting the global namespace.1681
227 unmodified lines