Add QUERY method support (#873)
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 f37e82c · Browse files · 10 files·+118 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+118 added−7 removed
- tests:+102 added−0 removed
- other:+16 added−7 removed
Provenance
- Commit
6edddd9- Tree
4f1948e- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
f37e82c
10 files changed+118 added−7 removed
modified:source/core/constants.ts+1 added-1 removed
34 unmodified lines35 export const supportsAbortSignal = typeof globalThis.AbortSignal === 'function' && typeof globalThis.AbortSignal.any === 'function';36 export const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';37 export const supportsFormData = typeof globalThis.FormData === 'function';38 39-export const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'] as const;39+export const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete', 'query'] as const;40 41 const validate = <T extends Array<true>>() => undefined as unknown as T;42 validate<[43 Expect<Equal<typeof requestMethods[number], RequestHttpMethod>>,241 unmodified linesmodified:source/types/ky.ts+8 added
68 unmodified lines69707172737475767778798081828384118 unmodified linesExpand all68 unmodified lines */ head: (url: Input, options?: Options) => ResponsePromise;
/** Fetch the given `url` using the option `{method: 'query'}`.
@param url - `Request` object, `URL` object, or URL string. @returns A promise with `Body` methods added. */ query: <T>(url: Input, options?: Options) => ResponsePromise<T>;
/** Create a new Ky instance with complete new defaults, without inheriting from any parent instance.
@returns A new Ky instance. */118 unmodified linesExpand allmodified:source/types/options.ts+2 added-2 removed
6 unmodified lines7 8 // eslint-disable-next-line unicorn/prevent-abbreviations9 export type SearchParamsOption = SearchParamsInit | Record<string, string | number | boolean | undefined> | Array<Array<string | number | boolean>>;10 11-export type RequestHttpMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';11+export type RequestHttpMethod = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'query';12 export type HttpMethod = LiteralUnion<RequestHttpMethod | 'options' | 'trace', string>;13 14 export type Input = string | URL | Request;15 383 unmodified lines399 export interface Options extends KyOptions, Omit<RequestInit, 'headers'> { // 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`.400 /**401 HTTP method used to make the request.402 403- Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.403+ Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.404 */405 method?: LiteralUnion<HttpMethod, string>;406 407 /**67 unmodified linesmodified:source/types/retry.ts+1 added-1 removed
21 unmodified lines22 23 /**24 The HTTP methods allowed to retry.25 26- @default ['get', 'put', 'head', 'delete', 'options', 'trace']26+ @default ['get', 'put', 'head', 'delete', 'options', 'trace', 'query']27 */28 methods?: HttpMethod[];29 30 /**145 unmodified linesmodified:source/utils/normalize.ts+1 added-1 removed
3 unmodified lines4 5 export const normalizeRequestMethod = (input: string): string =>6 requestMethods.includes(input as RequestHttpMethod) ? input.toUpperCase() : input;7 8-const retryMethods: HttpMethod[] = ['get', 'put', 'head', 'delete', 'options', 'trace'];8+const retryMethods: HttpMethod[] = ['get', 'put', 'head', 'delete', 'options', 'trace', 'query'];9 10 const retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];11 12 const retryAfterStatusCodes = [413, 429, 503];41 unmodified linesmodified:test/browser.ts+27 added
106 unmodified lines107 108 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'rainbow', 'rainbow', 'rainbow']);109 });110 111+defaultBrowsersTest('QUERY request', async (t: ExecutionContext, page: Page) => {112+ t.plan(2);113+114+ server.get('/', (_request, response) => {115+ response.end();116+ });117+118+ server.all('/test', (request, response) => {119+ t.is(request.method, 'QUERY');120+ response.json(request.body);121+ });122+123+ await page.goto(server.url);124+ await addKyScriptToPage(page);125+126+ const json = {127+ foo: true,128+ };129+130+ const result = await page.evaluate(async ({url, json}) => globalThis.ky.query(`${url}/test`, {json}).json(), {131+ url: server.url,132+ json,133+ });134+135+ t.deepEqual(result, json);136+});137+138 defaultBrowsersTest('aborting a request', async (t: ExecutionContext, page: Page) => {139 server.get('/', (_request, response) => {140 response.end('meow');141 });468 unmodified linesmodified:test/main.ts+20 added
111 unmodified lines112 113 t.is(await ky.delete(server.url).text(), 'DELETE');114 });115 116+test('QUERY request', async t => {117+ t.plan(3);118+119+ const server = await createHttpTestServer(t);120+ server.all('/', (request, response) => {121+ t.is(request.method, 'QUERY');122+ t.is(request.headers['content-type'], 'application/json');123+ response.json(request.body);124+ });125+126+ const json = {127+ foo: true,128+ };129+130+ const responseJson = await ky.query<typeof json>(server.url, {json}).json();131+132+ expectTypeOf(responseJson).toEqualTypeOf<typeof json>();133+ t.deepEqual(responseJson, json);134+});135+136 test('POST JSON', async t => {137 t.plan(2);138 139 const server = await createHttpTestServer(t);2364 unmodified linesmodified:test/methods.ts+20 added
41 unmodified lines42 }),43 );44 });45 46+test('QUERY method is normalized', async t => {47+ const server = await createHttpTestServer(t);48+ server.all('/', (_request, response) => {49+ response.end();50+ });51+52+ t.plan(1);53+54+ await ky(server.url, {55+ method: 'query',56+ hooks: {57+ beforeRequest: [58+ ({options}) => {59+ t.is(options.method, 'QUERY');60+ },61+ ],62+ },63+ });64+});65+66 test.failing('custom method remains identical', async t => {67 const server = await createHttpTestServer(t);68 server.all('/', (_request, response) => {69 response.end();28 unmodified linesmodified:test/retry.ts+35 added
87 unmodified lines88 });89 t.is(requestCount, 1);90 });91 92+test('QUERY retries by default', async t => {93+ let requestCount = 0;94+ const receivedBodies: unknown[] = [];95+ const receivedMethods: string[] = [];96+97+ const server = await createHttpTestServer(t);98+ server.all('/', (request, response) => {99+ requestCount++;100+ receivedMethods.push(request.method);101+ receivedBodies.push(request.body);102+103+ if (requestCount === defaultRetryCount + 1) {104+ response.json(request.body);105+ } else {106+ response.sendStatus(500);107+ }108+ });109+110+ const json = {111+ foo: true,112+ };113+114+ const result = await ky.query(server.url, {115+ json,116+ retry: {117+ delay: () => 0,118+ },119+ }).json();120+121+ t.deepEqual(result, json);122+ t.is(requestCount, defaultRetryCount + 1);123+ t.deepEqual(receivedMethods, ['QUERY', 'QUERY', 'QUERY']);124+ t.deepEqual(receivedBodies, [json, json, json]);125+});126+127 test('respect Retry-After: 0 and retry immediately', async t => {128 const retryCount = 4;129 let requestCount = 0;130 2171 unmodified linesmodified:readme.md+3 added-2 removed
171 unmodified lines172 ### ky.put(input, options?)173 ### ky.patch(input, options?)174 ### ky.head(input, options?)175 ### ky.delete(input, options?)176+### ky.query(input, options?)177 178 Sets `options.method` to the method name and makes a request.179 180 ⌨️ **TypeScript:** Accepts an optional type parameter for use with JSON responses (see [`ky()`](#kyinput-options)).18 unmodified lines199 Default: `'get'`200 201 HTTP method used to make the request.202 202-Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity.203+Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `DELETE`, and `QUERY`) are uppercased in order to avoid server errors due to case sensitivity.204 205 ##### json206 207 Type: `object` and any other value accepted by [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)69 unmodified lines277 278 Type: `object | number`\279 Default:280 - `limit`: `2`280-- `methods`: `get` `put` `head` `delete` `options` `trace`281+- `methods`: `get` `put` `head` `delete` `options` `trace` `query`282 - `statusCodes`: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)283 - `afterStatusCodes`: [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413), [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429), [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503)284 - `maxRetryAfter`: `Infinity`285 - `backoffLimit`: `Infinity`1583 unmodified lines