Skip to content
Myr

Add `replaceOption` helper for `.extend()` (#846)

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 1e38ff4 · Browse files · 4 files+490 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+490 added−4 removed

  • tests:+406 added−0 removed
  • other:+84 added−4 removed

4 files+490 added−4 removed

modified:source/utils/merge.ts+45 added-4 removed
modified:source/index.ts+1 added
79 unmodified lines
80 isNetworkError,81 isTimeoutError,82 isForceRetryError,83} from './utils/type-guards.js';84export {replaceOption} from './utils/merge.js';8586// Intentionally not exporting this for now as it's just an implementation detail and we don't want to commit to a certain API yet at least.87// export {NonError} from './errors/NonError.js';
modified:test/main.ts+406 added
5 unmodified lines
6 HTTPError,7 SchemaValidationError,8 TimeoutError,9 isKyError,10 replaceOption,11 type StandardSchemaV1,12} from '../source/index.js';13import {createHttpTestServer} from './helpers/create-http-test-server.js';14import {parseRawBody} from './helpers/parse-body.js';
1139 unmodified lines
1154 const {ok} = await extended.head(server.url);1155 t.true(ok);1156});11571158test('ky.extend() with replaceOption replaces hooks instead of appending', async t => {1159 const server = await createHttpTestServer(t);1160 server.get('/', (_request, response) => {1161 response.end();1162 });11631164 const callOrder: string[] = [];11651166 const base = ky.create({1167 hooks: {1168 beforeRequest: [1169 () => {1170 callOrder.push('base');1171 },1172 ],1173 },1174 });11751176 const extended = base.extend({1177 hooks: replaceOption({1178 beforeRequest: [1179 () => {1180 callOrder.push('extended');1181 },1182 ],1183 }),1184 });11851186 await extended(server.url);11871188 t.deepEqual(callOrder, ['extended']);1189});11901191test('ky.extend() with replaceOption replaces headers instead of merging', async t => {1192 const server = await createHttpTestServer(t);1193 server.get('/', (request, response) => {1194 response.json({1195 unicorn: request.headers.unicorn ?? null,1196 rainbow: request.headers.rainbow ?? null,1197 });1198 });11991200 const base = ky.create({1201 headers: {unicorn: 'unicorn', rainbow: 'rainbow'},1202 });12031204 const extended = base.extend({1205 headers: replaceOption({unicorn: 'new-unicorn'}),1206 });12071208 const json = await extended(server.url).json<Record<string, string | undefined>>();12091210 t.is(json.unicorn, 'new-unicorn');1211 t.is(json.rainbow, null);1212});12131214test('ky.extend() with replaceOption replaces searchParams instead of appending', async t => {1215 const server = await createHttpTestServer(t);1216 server.get('/', (request, response) => {1217 response.end(request.url);1218 });12191220 const base = ky.create({1221 searchParams: {a: '1', b: '2'},1222 });12231224 const extended = base.extend({1225 searchParams: replaceOption({c: '3'}),1226 });12271228 const text = await extended(server.url).text();12291230 t.true(text.includes('c=3'));1231 t.false(text.includes('a=1'));1232 t.false(text.includes('b=2'));1233});12341235test('ky.extend() with replaceOption works with function form', async t => {1236 const server = await createHttpTestServer(t);1237 server.get('/', (_request, response) => {1238 response.end();1239 });12401241 const callOrder: string[] = [];12421243 const base = ky.create({1244 hooks: {1245 beforeRequest: [1246 () => {1247 callOrder.push('base');1248 },1249 ],1250 },1251 });12521253 const extended = base.extend(() => ({1254 hooks: replaceOption({1255 beforeRequest: [1256 () => {1257 callOrder.push('extended');1258 },1259 ],1260 }),1261 }));12621263 await extended(server.url);12641265 t.deepEqual(callOrder, ['extended']);1266});12671268test('ky.extend() with replaceOption followed by normal extend appends correctly', async t => {1269 const server = await createHttpTestServer(t);1270 server.get('/', (_request, response) => {1271 response.end();1272 });12731274 const callOrder: string[] = [];12751276 const base = ky.create({1277 hooks: {1278 beforeRequest: [1279 () => {1280 callOrder.push('base');1281 },1282 ],1283 },1284 });12851286 const replaced = base.extend({1287 hooks: replaceOption({1288 beforeRequest: [1289 () => {1290 callOrder.push('replaced');1291 },1292 ],1293 }),1294 });12951296 const extended = replaced.extend({1297 hooks: {1298 beforeRequest: [1299 () => {1300 callOrder.push('appended');1301 },1302 ],1303 },1304 });13051306 await extended(server.url);13071308 t.deepEqual(callOrder, ['replaced', 'appended']);1309});13101311test('ky.extend() with replaceOption discards all parent hook types', async t => {1312 const server = await createHttpTestServer(t);1313 server.get('/', (_request, response) => {1314 response.end();1315 });13161317 const callOrder: string[] = [];13181319 const base = ky.create({1320 hooks: {1321 beforeRequest: [1322 () => {1323 callOrder.push('beforeRequest');1324 },1325 ],1326 afterResponse: [1327 () => {1328 callOrder.push('afterResponse');1329 },1330 ],1331 },1332 });13331334 // Replace hooks with only beforeRequest — afterResponse from parent should be gone1335 const extended = base.extend({1336 hooks: replaceOption({1337 beforeRequest: [1338 () => {1339 callOrder.push('replaced');1340 },1341 ],1342 }),1343 });13441345 await extended(server.url);13461347 t.deepEqual(callOrder, ['replaced']);1348});13491350test('ky.extend() with consecutive replaceOption calls each fully replace', async t => {1351 const server = await createHttpTestServer(t);1352 server.get('/', (_request, response) => {1353 response.end();1354 });13551356 const callOrder: string[] = [];13571358 const base = ky.create({1359 hooks: {1360 beforeRequest: [1361 () => {1362 callOrder.push('base');1363 },1364 ],1365 },1366 });13671368 const first = base.extend({1369 hooks: replaceOption({1370 beforeRequest: [1371 () => {1372 callOrder.push('first');1373 },1374 ],1375 }),1376 });13771378 const second = first.extend({1379 hooks: replaceOption({1380 beforeRequest: [1381 () => {1382 callOrder.push('second');1383 },1384 ],1385 }),1386 });13871388 await second(server.url);13891390 t.deepEqual(callOrder, ['second']);1391});13921393test('ky.extend() with replaceOption on headers followed by normal extend merges correctly', async t => {1394 const server = await createHttpTestServer(t);1395 server.get('/', (request, response) => {1396 response.json({1397 unicorn: request.headers.unicorn ?? null,1398 rainbow: request.headers.rainbow ?? null,1399 star: request.headers.star ?? null,1400 });1401 });14021403 const base = ky.create({1404 headers: {unicorn: 'unicorn', rainbow: 'rainbow'},1405 });14061407 const replaced = base.extend({1408 headers: replaceOption({star: 'star'}),1409 });14101411 // Normal extend after replace should merge with the replaced set1412 const extended = replaced.extend({1413 headers: {unicorn: 'new-unicorn'},1414 });14151416 const json = await extended(server.url).json<Record<string, string | undefined>>();14171418 t.is(json.unicorn, 'new-unicorn');1419 t.is(json.rainbow, null);1420 t.is(json.star, 'star');1421});14221423test('ky.extend() with replaceOption({}) clears headers', async t => {1424 const server = await createHttpTestServer(t);1425 server.get('/', (request, response) => {1426 response.json({1427 unicorn: request.headers.unicorn ?? null,1428 });1429 });14301431 const base = ky.create({1432 headers: {unicorn: 'unicorn'},1433 });14341435 const extended = base.extend({1436 headers: replaceOption({}),1437 });14381439 const json = await extended(server.url).json<Record<string, string | undefined>>();14401441 t.is(json.unicorn, null);1442});14431444test('ky.extend() with replaceOption on multiple options at once', async t => {1445 const server = await createHttpTestServer(t);1446 server.get('/', (request, response) => {1447 response.json({1448 unicorn: request.headers.unicorn ?? null,1449 url: request.url,1450 });1451 });14521453 const callOrder: string[] = [];14541455 const base = ky.create({1456 headers: {unicorn: 'unicorn'},1457 searchParams: {a: '1'},1458 hooks: {1459 beforeRequest: [1460 () => {1461 callOrder.push('base');1462 },1463 ],1464 },1465 });14661467 const extended = base.extend({1468 headers: replaceOption({accept: 'text/plain'}),1469 searchParams: replaceOption({b: '2'}),1470 hooks: replaceOption({1471 beforeRequest: [1472 () => {1473 callOrder.push('extended');1474 },1475 ],1476 }),1477 });14781479 const json = await extended(server.url).json<Record<string, string | undefined>>();14801481 t.is(json.unicorn, null);1482 t.true(json.url!.includes('b=2'));1483 t.false(json.url!.includes('a=1'));1484 t.deepEqual(callOrder, ['extended']);1485});14861487test('ky.extend() with replaceOption replaces context instead of merging', async t => {1488 const server = await createHttpTestServer(t);1489 server.get('/', (_request, response) => {1490 response.end();1491 });14921493 let capturedContext: Record<string, unknown> | undefined;14941495 const base = ky.create({1496 context: {a: 1, b: 2},1497 hooks: {1498 beforeRequest: [1499 ({options}) => {1500 capturedContext = options.context;1501 },1502 ],1503 },1504 });15051506 const extended = base.extend({1507 context: replaceOption({c: 3}),1508 });15091510 await extended(server.url);15111512 t.deepEqual(capturedContext, {c: 3});1513});15141515test('ky.extend() with replaceOption({}) clears hooks', async t => {1516 const server = await createHttpTestServer(t);1517 server.get('/', (_request, response) => {1518 response.end();1519 });15201521 const callOrder: string[] = [];15221523 const base = ky.create({1524 hooks: {1525 beforeRequest: [1526 () => {1527 callOrder.push('base');1528 },1529 ],1530 },1531 });15321533 const extended = base.extend({1534 hooks: replaceOption({}),1535 });15361537 await extended(server.url);15381539 t.deepEqual(callOrder, []);1540});15411542test('ky.extend() with replaceOption replaces retry instead of merging', async t => {1543 const server = await createHttpTestServer(t);1544 let requestCount = 0;1545 server.get('/', (_request, response) => {1546 requestCount++;1547 response.sendStatus(500);1548 });15491550 const base = ky.create({1551 retry: {limit: 3, delay: () => 1},1552 });15531554 const extended = base.extend({1555 retry: replaceOption({limit: 0}),1556 });15571558 await t.throwsAsync(extended(server.url));15591560 t.is(requestCount, 1);1561});15621563test('throws DOMException/Error with name AbortError when aborted by user', async t => {1564 const server = await createHttpTestServer(t);1565 // eslint-disable-next-line @typescript-eslint/no-empty-function1566 server.get('/', () => {});
270 unmodified lines
modified:readme.md+38 added
924 unmodified lines
925const response = await api.get('version');926//=> 'https://example.com/api/version'927```928929By default, `.extend()` deep-merges options: hooks are appended, headers are merged, and search parameters are accumulated. Use [`replaceOption`](#replaceoption) when you want to fully replace a merged property instead.930931```js932import ky, {replaceOption} from 'ky';933934const api = ky.create({935 hooks: {936 beforeRequest: [addAuth, addTracking],937 },938});939940// Appends as expected941const extended = api.extend({hooks: {beforeRequest: [logRequest]}});942// extended hooks.beforeRequest is [addAuth, addTracking, logRequest]943944// Replaces instead of appending945const replaced = api.extend({hooks: replaceOption({beforeRequest: [onlyThis]})});946// replaced hooks.beforeRequest is [onlyThis]947```948949### ky.create(defaultOptions)950951Create a new Ky instance with complete new defaults.952
295 unmodified lines
1248 }1249}1250```12511252### replaceOption12531254Wraps a value so that [`ky.extend()`](#kyextenddefaultoptions) will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.12551256```js1257import ky, {replaceOption} from 'ky';12581259const api = ky.create({1260 headers: {authorization: 'Bearer token', 'x-custom': 'value'},1261});12621263// Replace all headers instead of merging1264const publicApi = api.extend({1265 headers: replaceOption({accept: 'application/json'}),1266});1267// Headers are now just {accept: 'application/json'}1268```12691270## Tips12711272### Sending form data1273
321 unmodified lines