Skip to content
Myr

Preserve JSON types when cloning requests and responses

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 51b3177 · Browse files · 6 files+71 added−0 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+71 added−0 removed

  • tests:+38 added−0 removed
  • other:+33 added−0 removed

6 files+71 added−0 removed

modified:source/types/request.ts+1 added
modified:source/types/response.ts+1 added
modified:test/hooks.ts+24 added
62 unmodified lines
63});6465const requestFixtureUrl = 'about:blank';6667test('beforeRequest can inspect cloned JSON without consuming the outgoing body', async t => {68 const body = {name: 'Ada'};69 let inspected = false;70 const result = await ky.post('https://example.com', {71 json: body,72 hooks: {73 beforeRequest: [async ({request}) => {74 const clone = request.clone();75 const nestedClone = clone.clone();76 t.deepEqual(await clone.json<{name: string}>(), body);77 t.deepEqual(await nestedClone.json<{name: string}>(), body);78 t.false(request.bodyUsed);79 inspected = true;80 }],81 },82 async fetch(input) {83 t.true(inspected);84 return Response.json(await (input as Request).json());85 },86 }).json();8788 t.deepEqual(result, body);89});9091const createStreamBody = (text: string) => new ReadableStream<Uint8Array>({92 start(controller) {93 controller.enqueue(new TextEncoder().encode(text));94 controller.close();
6465 unmodified lines
modified:test/main.ts+14 added
26 unmodified lines
27 fetch: async () => new Response(''),28 }).json(undefined), {instanceOf: SyntaxError});29});3031test('typed response clones can independently parse the same JSON body', async t => {32 const response = await ky<{name: string}>('https://example.com', {33 fetch: async () => Response.json({name: 'Ada'}),34 });35 const clone = response.clone();36 const nestedClone = clone.clone();3738 t.false(response.bodyUsed);39 t.deepEqual(await clone.json(), {name: 'Ada'});40 t.false(response.bodyUsed);41 t.deepEqual(await nestedClone.json(), {name: 'Ada'});42 t.deepEqual(await response.json(), {name: 'Ada'});43});4445type TestSchemaResult<Output> = {value: Output} | {issues: Array<{message: string}>};4647const createSchema = <Output>(48 validate: (value: unknown) => TestSchemaResult<Output> | Promise<TestSchemaResult<Output>>,
3899 unmodified lines
added:test-d/request-clone.ts+19 added
added:test-d/response-clone.ts+12 added