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
Provenance
- Commit
3713ce8- Tree
f6bb7f5- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
1d15eb6
5 files changed+161 added−6 removed
modified:source/core/Ky.ts+8 added-5 removed
242 unmodified lines243 return schema === undefined ? undefined : validateJsonWithSchema(undefined, schema);244 }245 246 const jsonValue = options.parseJson247- ? await options.parseJson(text)247+ ? await options.parseJson(text, {request: ky.request, response})248 : JSON.parse(text);249 250 return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);251 };238 unmodified lines490 }491 492 #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 }496 497 return response;498 }11 unmodified lines510 if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {511 return text;512 }513 514- return this.#parseJson(text, errorDataTimeout);514+ return this.#parseJson(text, response, errorDataTimeout);515 }516 517 #isJsonContentType(contentType: string): boolean {518 // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.64 unmodified lines583 584 return result;585 }586 587- 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 linesmodified:source/types/options.ts+17 added-1 removed
39 unmodified lines40 41 /**42 User-defined JSON-parsing function.43 44+ The function receives the response text as the first argument and a context object as the second argument containing the `request` and `response`.45+46 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.50 51 @default JSON.parse()52 53 @example4 unmodified lines58 const json = await ky('https://example.com', {59 parseJson: text => bourne(text)60 }).json();61 ```62+63+ @example64+ ```65+ import ky from 'ky';66+67+ 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;77 78 /**79 User-defined JSON-stringifying function.80 359 unmodified linesmodified:test/http-error.ts+43 added
124 unmodified lines125 }));126 t.deepEqual(error?.data, {value: 1, custom: true});127 });128 129+test('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+ });135+136+ 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+});149+150+test('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+ });156+157+ 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+});171+172 test('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 linesmodified:test/main.ts+79 added
1862 unmodified lines1863 1864 t.false(isSchemaCalled());1865 });1866 1867+test('parseJson option receives context via .json() shortcut', async t => {1868+ const json = {hello: 'world'};1869+1870+ const server = await createHttpTestServer(t);1871+ server.get('/', (_request, response) => {1872+ response.json(json);1873+ });1874+1875+ 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();1886+1887+ t.deepEqual(responseJson, json);1888+});1889+1890+test('parseJson option receives context via response.json()', async t => {1891+ const json = {hello: 'world'};1892+1893+ const server = await createHttpTestServer(t);1894+ server.get('/', (_request, response) => {1895+ response.json(json);1896+ });1897+1898+ 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+ });1907+1908+ const responseJson = await response.json();1909+ t.deepEqual(responseJson, json);1910+});1911+1912+test('parseJson option receives context after retry', async t => {1913+ let requestCount = 0;1914+ const statuses: number[] = [];1915+1916+ 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+ }1923+1924+ response.json({hello: 'world'});1925+ });1926+1927+ 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();1939+1940+ 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+});1945+1946 test('stringifyJson option with request.json()', async t => {1947 const server = await createHttpTestServer(t, {bodyParser: false});1948 1949 const json = {hello: 'world'};13 unmodified linesmodified:readme.md+14 added
732 unmodified lines733 Default: `JSON.parse()`734 735 User-defined JSON-parsing function.736 737+The 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)).738+739 Use-cases:740 1. Parse JSON via the [`bourne` package](https://github.com/hapijs/bourne) to protect from prototype pollution.741 2. Parse JSON with [`reviver` option of `JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).742+3. Log or handle JSON parse errors with request context.743 744 ```js745 import ky from 'ky';746 import bourne from '@hapijs/bourne';2 unmodified lines749 parseJson: text => bourne(text)750 }).json();751 ```752 753+```js754+import ky from 'ky';755+756+const 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+```763+764 ##### stringifyJson765 766 Type: `Function`\767 Default: `JSON.stringify()`843 unmodified lines