Add typed JSON response (#437)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dominik · committed by GitHub · parent f34fb1f · Browse files · 7 files·+51 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+51 added−40 removed
- tests:+5 added−1 removed
- other:+46 added−39 removed
Provenance
- Commit
cff4c7a- Tree
87c4174- Author
Dominik <16338782+TeraNovaLP@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
f34fb1f
7 files changed+51 added−40 removed
modified:source/core/Ky.ts+1 added-1 removed
1 import {HTTPError} from '../errors/HTTPError.js';2 import {TimeoutError} from '../errors/TimeoutError.js';3 import type {Hooks} from '../types/hooks.js';4 import type {Input, InternalOptions, NormalizedOptions, Options, SearchParamsInit} from '../types/options.js';5-import {ResponsePromise} from '../types/response.js';5+import {ResponsePromise} from '../types/ResponsePromise.js';6 import {deepMerge, mergeHeaders} from '../utils/merge.js';7 import {normalizeRequestMethod, normalizeRetryOptions} from '../utils/normalize.js';8 import {delay, timeout, TimeoutOptions} from '../utils/time.js';9 import {ObjectEntries} from '../utils/types.js';315 unmodified linesmodified:source/types/ky.ts+1 added-1 removed
12334567113 unmodified linesExpand allimport {stop} from '../core/constants.js';import type {Input, Options} from './options.js';import type {ResponsePromise} from './response.js';import type {ResponsePromise} from './ResponsePromise.js';
export interface KyInstance { /** Fetch the given `url`.113 unmodified linesExpand allmodified:source/types/response.ts+1 added-35 removed
1234567891011121314151617181920212223242526272829303132331235363/**Returns a `Response` object with `Body` methods 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 the response status is `204` instead of throwing a parse error due to an empty body.*/export interface ResponsePromise extends Promise<Response> { arrayBuffer: () => Promise<ArrayBuffer>;
blob: () => Promise<Blob>;
formData: () => Promise<FormData>;
// 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.
@example ``` import ky from 'ky';
const json = await ky(…).json(); ```
@example ``` import ky from 'ky';
interface Result { value: number; }
const result = await ky(…).json<Result>(); ``` */export interface KyResponse extends Response { json: <T = unknown>() => Promise<T>;
text: () => Promise<string>;}added:source/types/ResponsePromise.ts+39 added
123456789101112131415161718192021222324252627282930313233343536373839/**Returns a `Response` object with `Body` methods 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 the response status is `204` instead of throwing a parse error due to an empty body.*/import {KyResponse} from './response.js';
export interface ResponsePromise extends Promise<KyResponse> { arrayBuffer: () => Promise<ArrayBuffer>;
blob: () => Promise<Blob>;
formData: () => Promise<FormData>;
// 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.
@example ``` import ky from 'ky';
const json = await ky(…).json(); ```
@example ``` import ky from 'ky';
interface Result { value: number; }
const result = await ky(…).json<Result>(); ``` */ json: <T = unknown>() => Promise<T>;
text: () => Promise<string>;}modified:source/index.ts+2 added-1 removed
42 unmodified lines43 BeforeErrorHook,44 AfterResponseHook,45 } from './types/hooks.js';46 47-export {ResponsePromise} from './types/response.js';47+export {ResponsePromise} from './types/ResponsePromise.js';48+export {KyResponse} from './types/response.js';49 export {HTTPError} from './errors/HTTPError.js';50 export {TimeoutError} from './errors/TimeoutError.js';modified:test/main.ts+5 added-1 removed
1 import {Buffer} from 'node:buffer';2 import test from 'ava';3 import delay from 'delay';4+import {expectTypeOf} from 'expect-type';5 import ky, {TimeoutError} from '../source/index.js';6 import {createHttpTestServer} from './helpers/create-http-test-server.js';7 import {parseRawBody} from './helpers/parse-body.js';8 653 unmodified lines662 ...JSON.parse(text),663 extra: 'extraValue',664 }),665 });665- const responseJson = await response.json();666 667+ const responseJson = await response.json<{hello: string; extra: string}>();668+669+ expectTypeOf(responseJson).toMatchTypeOf({hello: 'world', extra: 'extraValue'});670+671 t.deepEqual(responseJson, {672 ...json,673 extra: 'extraValue',674 });28 unmodified linesmodified:package.json+2 added-1 removed
69 unmodified lines70 "playwright-chromium": "^1.19.2",71 "raw-body": "^2.5.1",72 "ts-node": "^10.6.0",73 "typescript": "~4.6.2",74- "xo": "^0.48.0"74+ "xo": "^0.48.0",75+ "expect-type": "^0.13.0"76 },77 "sideEffects": false,78 "xo": {79 "envs": [40 unmodified lines