Skip to content
Myr

Add request/response context to `parseJson` option (#849)

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 1d15eb6 · Browse files · 5 files+161 added−6 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+161 added−6 removed

  • tests:+122 added−0 removed
  • other:+39 added−6 removed

5 files+161 added−6 removed

modified:source/core/Ky.ts+8 added-5 removed
242 unmodified lines
243 return schema === undefined ? undefined : validateJsonWithSchema(undefined, schema);244 }245246 const jsonValue = options.parseJson247 ? await options.parseJson(text)247 ? await options.parseJson(text, {request: ky.request, response})248 : JSON.parse(text);249250 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);251 };
238 unmodified lines
490 }491492 #decorateResponse(response: Response): Response {493 if (this.#options.parseJson) {494 response.json = async () => this.#options.parseJson!(await response.text());494 response.json = async () => this.#options.parseJson!(await response.text(), {request: this.request, response});495 }496497 return response;498 }
11 unmodified lines
510 if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {511 return text;512 }513514 return this.#parseJson(text, errorDataTimeout);514 return this.#parseJson(text, response, errorDataTimeout);515 }516517 #isJsonContentType(contentType: string): boolean {518 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.
64 unmodified lines
583584 return result;585 }586587 async #parseJson(text: string, timeoutMs: number): Promise<unknown> {587 async #parseJson(text: string, response: Response, timeoutMs: number): Promise<unknown> {588 let timeoutId: ReturnType<typeof setTimeout> | undefined;589 try {590 return await Promise.race([591 Promise.resolve().then(() => (this.#options.parseJson ?? JSON.parse)(text)),591 Promise.resolve().then(() => this.#options.parseJson592 ? this.#options.parseJson(text, {request: this.request, response})593 : JSON.parse(text),594 ),595 new Promise<undefined>(resolve => {596 timeoutId = setTimeout(() => {597 resolve(undefined);598 }, timeoutMs);
290 unmodified lines
modified:source/types/options.ts+17 added-1 removed
39 unmodified lines
4041 /**42 User-defined JSON-parsing function.4344 The function receives the response text as the first argument and a context object as the second argument containing the `request` and `response`.4546 Use-cases:47 1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.48 2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).49 3. Log or handle JSON parse errors with request context.5051 @default JSON.parse()5253 @example
4 unmodified lines
58 const json = await ky('https://example.com', {59 parseJson: text => bourne(text)60 }).json();61 ```6263 @example64 ```65 import ky from 'ky';6667 const json = await ky('https://example.com', {68 parseJson: (text, {request, response}) => {69 console.log(`Parsing JSON from ${request.url} (status: ${response.status})`);70 return JSON.parse(text);71 }72 }).json();73 ```74 */60 parseJson?: (text: string) => unknown;75 // `options` is intentionally not included in the context to avoid exposing Ky internals through a parsing callback. `request`/`response` already provide the metadata needed for logging.76 parseJson?: (text: string, context: {request: Request; response: Response}) => unknown;7778 /**79 User-defined JSON-stringifying function.80
359 unmodified lines
modified:test/http-error.ts+43 added
124 unmodified lines
125 }));126 t.deepEqual(error?.data, {value: 1, custom: true});127});128129test('HTTPError#data parseJson receives context', async t => {130 const server = await createHttpTestServer(t);131 const body = {value: 1};132 server.get('/', (_request, response) => {133 response.status(400).json(body);134 });135136 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {137 parseJson(text, {request, response}) {138 t.true(request instanceof Request);139 t.true(response instanceof Response);140 t.is(response.status, 400);141 t.true(request.url.includes(server.url));142 const data = JSON.parse(text) as Record<string, unknown>;143 data.custom = true;144 return data;145 },146 }));147 t.deepEqual(error?.data, {value: 1, custom: true});148});149150test('HTTPError#data async parseJson receives context', async t => {151 const server = await createHttpTestServer(t);152 const body = {value: 1};153 server.get('/', (_request, response) => {154 response.status(400).json(body);155 });156157 const error = await t.throwsAsync<HTTPError>(ky.get(server.url, {158 async parseJson(text, {request, response}) {159 t.true(request instanceof Request);160 t.true(response instanceof Response);161 t.is(response.status, 400);162 t.true(request.url.includes(server.url));163 await Promise.resolve();164 const data = JSON.parse(text) as Record<string, unknown>;165 data.custom = true;166 return data;167 },168 }));169 t.deepEqual(error?.data, {value: 1, custom: true});170});171172test('HTTPError#data awaits async parseJson option', async t => {173 const server = await createHttpTestServer(t);174 const body = {value: 1};175 server.get('/', (_request, response) => {
406 unmodified lines
modified:test/main.ts+79 added
1862 unmodified lines
18631864 t.false(isSchemaCalled());1865});18661867test('parseJson option receives context via .json() shortcut', async t => {1868 const json = {hello: 'world'};18691870 const server = await createHttpTestServer(t);1871 server.get('/', (_request, response) => {1872 response.json(json);1873 });18741875 const responseJson = await ky1876 .get(server.url, {1877 parseJson(text, {request, response}) {1878 t.true(request instanceof Request);1879 t.true(response instanceof Response);1880 t.is(response.status, 200);1881 t.true(request.url.includes(server.url));1882 return JSON.parse(text);1883 },1884 })1885 .json();18861887 t.deepEqual(responseJson, json);1888});18891890test('parseJson option receives context via response.json()', async t => {1891 const json = {hello: 'world'};18921893 const server = await createHttpTestServer(t);1894 server.get('/', (_request, response) => {1895 response.json(json);1896 });18971898 const response = await ky.get(server.url, {1899 parseJson(text, {request, response}) {1900 t.true(request instanceof Request);1901 t.true(response instanceof Response);1902 t.is(response.status, 200);1903 t.true(request.url.includes(server.url));1904 return JSON.parse(text);1905 },1906 });19071908 const responseJson = await response.json();1909 t.deepEqual(responseJson, json);1910});19111912test('parseJson option receives context after retry', async t => {1913 let requestCount = 0;1914 const statuses: number[] = [];19151916 const server = await createHttpTestServer(t);1917 server.get('/', (_request, response) => {1918 requestCount++;1919 if (requestCount === 1) {1920 response.status(500).json({error: 'fail'});1921 return;1922 }19231924 response.json({hello: 'world'});1925 });19261927 const responseJson = await ky1928 .get(server.url, {1929 retry: 1,1930 parseJson(text, {request, response}) {1931 t.true(request instanceof Request);1932 t.true(response instanceof Response);1933 t.true(request.url.includes(server.url));1934 statuses.push(response.status);1935 return JSON.parse(text);1936 },1937 })1938 .json();19391940 t.deepEqual(responseJson, {hello: 'world'});1941 t.is(requestCount, 2);1942 // ParseJson is called for the error response (HTTPError#data) and the success response1943 t.deepEqual(statuses, [500, 200]);1944});19451946test('stringifyJson option with request.json()', async t => {1947 const server = await createHttpTestServer(t, {bodyParser: false});19481949 const json = {hello: 'world'};
13 unmodified lines
modified:readme.md+14 added
732 unmodified lines
733Default: `JSON.parse()`734735User-defined JSON-parsing function.736737The function receives the response text as the first argument and a context object as the second argument containing the `request` ([`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)) and `response` ([`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)).738739Use-cases:7401. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.7412. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).7423. Log or handle JSON parse errors with request context.743744```js745import ky from 'ky';746import bourne from '@hapijs/bourne';
2 unmodified lines
749 parseJson: text => bourne(text)750}).json();751```752753```js754import ky from 'ky';755756const json = await ky('https://example.com', {757 parseJson: (text, {request, response}) => {758 console.log(`Parsing JSON from ${request.url} (status: ${response.status})`);759 return JSON.parse(text);760 }761}).json();762```763764##### stringifyJson765766Type: `Function`\767Default: `JSON.stringify()`
843 unmodified lines