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
Provenance
- Commit
bb8412e- Tree
aa30a71- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
1e38ff4
4 files changed+490 added−4 removed
modified:source/utils/merge.ts+45 added-4 removed
12345678910111213141516171819202122232425262728293031323334353637383940106 unmodified linesExpand all14714814915015115212015315415515615715815916016116216316416516616716816917017117217313917417517617717817918018118218314718418518618718818919019115219219319419519619720 unmodified linesimport type {KyHeadersInit, Options} from '../types/options.js';import type {Hooks} from '../types/hooks.js';import {supportsAbortSignal} from '../core/constants.js';import {isObject} from './is.js';
const replaceSymbol: unique symbol = Symbol('replaceOption');
const isReplaceMarked = (value: unknown): boolean => isObject(value) && (value as any)[replaceSymbol] === true;
/**Wraps a value so that `ky.extend()` will replace the parent value instead of merging with it.
By default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.
@example```import ky, {replaceOption} from 'ky';
const base = ky.create({ hooks: {beforeRequest: [addAuth, addTracking]},});
// Replaces instead of appendingconst extended = base.extend({ hooks: replaceOption({beforeRequest: [onlyThis]}),});// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]```*/export const replaceOption = <T extends Record<string, unknown>>(value: T): T => { const copy = {...value}; Object.defineProperty(copy, replaceSymbol, {value: true, enumerable: false}); return copy as T;};
export const validateAndMerge = (...sources: Array<Partial<Options> | undefined>): Partial<Options> => { for (const source of sources) { if ((!isObject(source) || Array.isArray(source)) && source !== undefined) { throw new TypeError('The `options` argument must be an object');106 unmodified linesExpand all returnValue = { ...returnValue, context: (value === undefined || value === null) ? {} : (isReplaceMarked(value) ? {...value} : {...returnValue.context, ...value}, : {...returnValue.context, ...value}), }; continue; }
// Special handling for searchParams if (key === 'searchParams') { if (value === undefined || value === null) { // Explicit undefined or null removes searchParams searchParameters = undefined; } else if (isReplaceMarked(value)) { searchParameters = {...value}; } else { // First source: keep as-is to preserve type (string/object/URLSearchParams) // Subsequent sources: merge and convert to URLSearchParams searchParameters = searchParameters === undefined ? value : appendSearchParameters(searchParameters, value); }
continue; }
if (isObject(value) && key in returnValue) { if (isObject(value) && !isReplaceMarked(value) && key in returnValue) { value = deepMerge(returnValue[key], value); }
returnValue = {...returnValue, [key]: value}; }
if (isObject((source as any).hooks)) { hooks = isReplaceMarked((source as any).hooks) ? mergeHooks({}, (source as any).hooks) hooks = mergeHooks(hooks, (source as any).hooks); : mergeHooks(hooks, (source as any).hooks);
returnValue.hooks = hooks; }
if (isObject((source as any).headers)) { headers = isReplaceMarked((source as any).headers) ? new globalThis.Headers({...(source as any).headers} as RequestInit['headers']) headers = mergeHeaders(headers, (source as any).headers); : mergeHeaders(headers, (source as any).headers);
returnValue.headers = headers; } } }20 unmodified linesmodified:source/index.ts+1 added
79 unmodified lines80 isNetworkError,81 isTimeoutError,82 isForceRetryError,83 } from './utils/type-guards.js';84+export {replaceOption} from './utils/merge.js';85 86 // 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 lines6 HTTPError,7 SchemaValidationError,8 TimeoutError,9 isKyError,10+ replaceOption,11 type StandardSchemaV1,12 } from '../source/index.js';13 import {createHttpTestServer} from './helpers/create-http-test-server.js';14 import {parseRawBody} from './helpers/parse-body.js';1139 unmodified lines1154 const {ok} = await extended.head(server.url);1155 t.true(ok);1156 });1157 1158+test('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+ });1163+1164+ const callOrder: string[] = [];1165+1166+ const base = ky.create({1167+ hooks: {1168+ beforeRequest: [1169+ () => {1170+ callOrder.push('base');1171+ },1172+ ],1173+ },1174+ });1175+1176+ const extended = base.extend({1177+ hooks: replaceOption({1178+ beforeRequest: [1179+ () => {1180+ callOrder.push('extended');1181+ },1182+ ],1183+ }),1184+ });1185+1186+ await extended(server.url);1187+1188+ t.deepEqual(callOrder, ['extended']);1189+});1190+1191+test('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+ });1199+1200+ const base = ky.create({1201+ headers: {unicorn: 'unicorn', rainbow: 'rainbow'},1202+ });1203+1204+ const extended = base.extend({1205+ headers: replaceOption({unicorn: 'new-unicorn'}),1206+ });1207+1208+ const json = await extended(server.url).json<Record<string, string | undefined>>();1209+1210+ t.is(json.unicorn, 'new-unicorn');1211+ t.is(json.rainbow, null);1212+});1213+1214+test('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+ });1219+1220+ const base = ky.create({1221+ searchParams: {a: '1', b: '2'},1222+ });1223+1224+ const extended = base.extend({1225+ searchParams: replaceOption({c: '3'}),1226+ });1227+1228+ const text = await extended(server.url).text();1229+1230+ t.true(text.includes('c=3'));1231+ t.false(text.includes('a=1'));1232+ t.false(text.includes('b=2'));1233+});1234+1235+test('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+ });1240+1241+ const callOrder: string[] = [];1242+1243+ const base = ky.create({1244+ hooks: {1245+ beforeRequest: [1246+ () => {1247+ callOrder.push('base');1248+ },1249+ ],1250+ },1251+ });1252+1253+ const extended = base.extend(() => ({1254+ hooks: replaceOption({1255+ beforeRequest: [1256+ () => {1257+ callOrder.push('extended');1258+ },1259+ ],1260+ }),1261+ }));1262+1263+ await extended(server.url);1264+1265+ t.deepEqual(callOrder, ['extended']);1266+});1267+1268+test('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+ });1273+1274+ const callOrder: string[] = [];1275+1276+ const base = ky.create({1277+ hooks: {1278+ beforeRequest: [1279+ () => {1280+ callOrder.push('base');1281+ },1282+ ],1283+ },1284+ });1285+1286+ const replaced = base.extend({1287+ hooks: replaceOption({1288+ beforeRequest: [1289+ () => {1290+ callOrder.push('replaced');1291+ },1292+ ],1293+ }),1294+ });1295+1296+ const extended = replaced.extend({1297+ hooks: {1298+ beforeRequest: [1299+ () => {1300+ callOrder.push('appended');1301+ },1302+ ],1303+ },1304+ });1305+1306+ await extended(server.url);1307+1308+ t.deepEqual(callOrder, ['replaced', 'appended']);1309+});1310+1311+test('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+ });1316+1317+ const callOrder: string[] = [];1318+1319+ 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+ });1333+1334+ // 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+ });1344+1345+ await extended(server.url);1346+1347+ t.deepEqual(callOrder, ['replaced']);1348+});1349+1350+test('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+ });1355+1356+ const callOrder: string[] = [];1357+1358+ const base = ky.create({1359+ hooks: {1360+ beforeRequest: [1361+ () => {1362+ callOrder.push('base');1363+ },1364+ ],1365+ },1366+ });1367+1368+ const first = base.extend({1369+ hooks: replaceOption({1370+ beforeRequest: [1371+ () => {1372+ callOrder.push('first');1373+ },1374+ ],1375+ }),1376+ });1377+1378+ const second = first.extend({1379+ hooks: replaceOption({1380+ beforeRequest: [1381+ () => {1382+ callOrder.push('second');1383+ },1384+ ],1385+ }),1386+ });1387+1388+ await second(server.url);1389+1390+ t.deepEqual(callOrder, ['second']);1391+});1392+1393+test('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+ });1402+1403+ const base = ky.create({1404+ headers: {unicorn: 'unicorn', rainbow: 'rainbow'},1405+ });1406+1407+ const replaced = base.extend({1408+ headers: replaceOption({star: 'star'}),1409+ });1410+1411+ // Normal extend after replace should merge with the replaced set1412+ const extended = replaced.extend({1413+ headers: {unicorn: 'new-unicorn'},1414+ });1415+1416+ const json = await extended(server.url).json<Record<string, string | undefined>>();1417+1418+ t.is(json.unicorn, 'new-unicorn');1419+ t.is(json.rainbow, null);1420+ t.is(json.star, 'star');1421+});1422+1423+test('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+ });1430+1431+ const base = ky.create({1432+ headers: {unicorn: 'unicorn'},1433+ });1434+1435+ const extended = base.extend({1436+ headers: replaceOption({}),1437+ });1438+1439+ const json = await extended(server.url).json<Record<string, string | undefined>>();1440+1441+ t.is(json.unicorn, null);1442+});1443+1444+test('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+ });1452+1453+ const callOrder: string[] = [];1454+1455+ 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+ });1466+1467+ 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+ });1478+1479+ const json = await extended(server.url).json<Record<string, string | undefined>>();1480+1481+ 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+});1486+1487+test('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+ });1492+1493+ let capturedContext: Record<string, unknown> | undefined;1494+1495+ const base = ky.create({1496+ context: {a: 1, b: 2},1497+ hooks: {1498+ beforeRequest: [1499+ ({options}) => {1500+ capturedContext = options.context;1501+ },1502+ ],1503+ },1504+ });1505+1506+ const extended = base.extend({1507+ context: replaceOption({c: 3}),1508+ });1509+1510+ await extended(server.url);1511+1512+ t.deepEqual(capturedContext, {c: 3});1513+});1514+1515+test('ky.extend() with replaceOption({}) clears hooks', async t => {1516+ const server = await createHttpTestServer(t);1517+ server.get('/', (_request, response) => {1518+ response.end();1519+ });1520+1521+ const callOrder: string[] = [];1522+1523+ const base = ky.create({1524+ hooks: {1525+ beforeRequest: [1526+ () => {1527+ callOrder.push('base');1528+ },1529+ ],1530+ },1531+ });1532+1533+ const extended = base.extend({1534+ hooks: replaceOption({}),1535+ });1536+1537+ await extended(server.url);1538+1539+ t.deepEqual(callOrder, []);1540+});1541+1542+test('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+ });1549+1550+ const base = ky.create({1551+ retry: {limit: 3, delay: () => 1},1552+ });1553+1554+ const extended = base.extend({1555+ retry: replaceOption({limit: 0}),1556+ });1557+1558+ await t.throwsAsync(extended(server.url));1559+1560+ t.is(requestCount, 1);1561+});1562+1563 test('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 linesmodified:readme.md+38 added
924 unmodified lines925 const response = await api.get('version');926 //=> 'https://example.com/api/version'927 ```928 929+By 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.930+931+```js932+import ky, {replaceOption} from 'ky';933+934+const api = ky.create({935+ hooks: {936+ beforeRequest: [addAuth, addTracking],937+ },938+});939+940+// Appends as expected941+const extended = api.extend({hooks: {beforeRequest: [logRequest]}});942+// extended hooks.beforeRequest is [addAuth, addTracking, logRequest]943+944+// Replaces instead of appending945+const replaced = api.extend({hooks: replaceOption({beforeRequest: [onlyThis]})});946+// replaced hooks.beforeRequest is [onlyThis]947+```948+949 ### ky.create(defaultOptions)950 951 Create a new Ky instance with complete new defaults.952 295 unmodified lines1248 }1249 }1250 ```1251 1252+### replaceOption1253+1254+Wraps 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.1255+1256+```js1257+import ky, {replaceOption} from 'ky';1258+1259+const api = ky.create({1260+ headers: {authorization: 'Bearer token', 'x-custom': 'value'},1261+});1262+1263+// Replace all headers instead of merging1264+const publicApi = api.extend({1265+ headers: replaceOption({accept: 'application/json'}),1266+});1267+// Headers are now just {accept: 'application/json'}1268+```1269+1270 ## Tips1271 1272 ### Sending form data1273 321 unmodified lines