formdata-searchparams.ts
This file
Path
test/formdata-searchparams.ts
185 lines · 5.7 KiB · TypeScript
Last changed by
Improve docsSindre Sorhusbefore adoption8778439
History of this fileTake it
The walk stopped after 200 commits: lines older than 37fc250 point at it.
Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 1–5why, one step back1import test from 'ava';2import ky from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';45test('FormData with searchParams and onUploadProgress', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 6why, one step back6 const server = await createHttpTestServer(t);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 7–57why, one step back78 server.post('/', (request, response) => {9 const url = new URL(request.url!, `http://${request.headers.host}`);1011 let body = '';12 request.on('data', chunk => {13 body += chunk; // eslint-disable-line @typescript-eslint/restrict-plus-operands14 });1516 request.on('end', () => {17 response.json({18 params: Object.fromEntries(url.searchParams),19 bodyLength: body.length,20 contentType: request.headers['content-type'] ?? '',21 });22 });23 });2425 const formData = new FormData();26 formData.append('field', 'value');27 formData.append('file', new Blob(['test content'], {type: 'text/plain'}), 'test.txt');2829 let wasProgressCalled = false;30 let lastProgress = 0;3132 const response = await ky.post(server.url, {33 body: formData,34 searchParams: {35 foo: 'bar',36 test: '123',37 },38 onUploadProgress(progress) {39 wasProgressCalled = true;40 lastProgress = progress.percent;41 },42 }).json<{params: Record<string, string>; bodyLength: number; contentType: string}>();4344 // Check that searchParams were added to URL45 t.is(response.params.foo, 'bar');46 t.is(response.params.test, '123');4748 // Check that FormData body was sent (should be multipart with content)49 t.true(response.bodyLength > 0, 'Body should not be empty');50 t.true(response.contentType.includes('multipart/form-data'), 'Should have multipart content-type');5152 // Check that progress callback was called53 t.true(wasProgressCalled, 'Upload progress callback should have been called');54 t.is(lastProgress, 1, 'Final progress should be 100%');55});5657test('retries with FormData in afterResponse hook maintains correct boundary', async t => {Simplify testsSindre Sorhusbefore adoptiondfa3f59
line 58why, one step back58 const server = await createHttpTestServer(t);Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 59–99why, one step back5960 let requestCount = 0;61 const receivedBoundaries: string[] = [];6263 server.post('/', (request, response) => {64 requestCount++;6566 const contentType = request.headers['content-type'] ?? '';67 const boundaryMatch = /boundary=([^;]+)/.exec(contentType);68 const headerBoundary = boundaryMatch?.[1];6970 let body = '';71 request.on('data', chunk => {72 body += chunk.toString(); // eslint-disable-line @typescript-eslint/restrict-plus-operands73 });7475 request.on('end', () => {76 // Extract boundary from actual body content77 const bodyBoundaryMatch = /^--([^\r\n]+)/.exec(body);78 const bodyBoundary = bodyBoundaryMatch?.[1];7980 receivedBoundaries.push(`header:${headerBoundary},body:${bodyBoundary}`);8182 if (requestCount === 1) {83 // First request fails with 40184 response.status(401).end();85 } else {86 // Second request succeeds - verify boundary matches87 const boundariesMatch = headerBoundary === bodyBoundary;88 response.json({success: boundariesMatch});89 }90 });91 });9293 const formData = new FormData();94 formData.append('field', 'value');9596 const result = await ky.post(server.url, {97 body: formData,98 hooks: {99 afterResponse: [Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e
line 100why, one step back100 async ({request, options, response}) => {Add retry count to `afterResponse` and `beforeError` hooks (#763)Sindre Sorhusbefore adoption37fc250
lines 101–111why, one step back101 if (response.status === 401) {102 return ky(request, options);103 }104 },105 ],106 },107 }).json<{success: boolean}>();108109 t.is(requestCount, 2, 'Should make 2 requests');110 t.true(result.success, 'Content-type boundary should match body boundary on retry');111});Detect request stream support in Bun and Deno, and cover the pipeline with testsSindre Sorhusbefore adoption83c711c
lines 112–143why, one step back112113// Fetch §5.2 requires the multipart payload and its Content-Type header to share one boundary.114test('replacing a Request input body keeps the multipart boundary consistent', async t => {115 const server = await createHttpTestServer(t);116117 let headerBoundary: string | undefined;118 let bodyBoundary: string | undefined;119 server.post('/', (request, response) => {120 headerBoundary = /boundary=([^;]+)/.exec(request.headers['content-type'] ?? '')?.[1];121122 let body = '';123 request.on('data', chunk => {124 body += chunk.toString(); // eslint-disable-line @typescript-eslint/restrict-plus-operands125 });126127 request.on('end', () => {128 bodyBoundary = /^--([^\r\n]+)/.exec(body)?.[1];129 response.end();130 });131 });132133 const request = new Request(server.url, {method: 'POST', body: 'original'});134 const replacement = new FormData();135 replacement.append('field', 'value');136137 await ky(request, {138 body: replacement,139 searchParams: {a: '1'},140 });141142 t.is(headerBoundary, bodyBoundary, 'Header boundary must match the body boundary');143});Improve docsSindre Sorhusbefore adoption8778439
lines 144–185why, one step back144145// A hook can replace the request body, as in the "Modifying FormData in hooks" example. The body of the replaced request must not be cancelled, because the runtime may still read it to serialize the replacement body.146test('a hook can replace a FormData body', async t => {147 const server = await createHttpTestServer(t);148149 let headerBoundary: string | undefined;150 let body = '';151 server.post('/', (request, response) => {152 headerBoundary = /boundary=([^;]+)/.exec(request.headers['content-type'] ?? '')?.[1];153154 request.on('data', chunk => {155 body += chunk.toString(); // eslint-disable-line @typescript-eslint/restrict-plus-operands156 });157158 request.on('end', () => {159 response.end();160 });161 });162163 const formData = new FormData();164 formData.append('Food', 'fries');165166 await ky.post(server.url, {167 body: formData,168 hooks: {169 beforeRequest: [({request}) => {170 const replacement = new FormData();171 for (const [key, value] of formData) {172 replacement.set(key.toLowerCase(), value);173 }174175 request.headers.delete('content-type');176 return new Request(request, {body: replacement});177 }],178 },179 });180181 t.truthy(headerBoundary);182 t.is(`--${headerBoundary}`, body.slice(0, headerBoundary.length + 2), 'Header boundary must match the body boundary');183 t.true(body.includes('name="food"'), 'The replacement fields must be sent');184 t.false(body.includes('name="Food"'), 'The replaced fields must not be sent');185});