Skip to content
Myr

Report a `hooks` option that is not an object

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 3f0e330 · Browse files · 2 files+88 added−8 removed
This commit

State

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

Diff stats

2 files+88 added−8 removed

  • tests:+68 added−0 removed
  • other:+20 added−8 removed

2 files+88 added−8 removed

modified:source/utils/merge.ts+20 added-8 removed
190 unmodified lines
191 }192193 // A single hook type can be wrapped in `replaceOption()` to replace only that array instead of the whole `hooks` object.194 const {isReplace, value} = getReplaceState(incoming[property]);195 if (value !== undefined && !Array.isArray(value)) {196 // Merging ignores anything that is neither an array nor an object, so a single function, a string or `null`197 // used to be dropped without a word and the hook simply never ran.198 throw new TypeError(`\`hooks.${property}\` must be an array`);199 }200201 if (isReplace) {202 return [...(value ?? [])] as NormalizedHooks[K];203 }204205 return deepMerge<NormalizedHooks[K]>(original[property] ?? [], value ?? []);206}207202export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => (203 {204 init: newHookValue(original, incoming, 'init'),205 beforeRequest: newHookValue(original, incoming, 'beforeRequest'),206 beforeRetry: newHookValue(original, incoming, 'beforeRetry'),207 beforeError: newHookValue(original, incoming, 'beforeError'),208 afterResponse: newHookValue(original, incoming, 'afterResponse'),208export const mergeHooks = (original: Hooks = {}, incoming: Hooks = {}): NormalizedHooks => {209 // `null` selects the default, the same way option merging treats a nullish value as absent.210 const incomingHooks = incoming ?? {};211 if (!isObject(incomingHooks)) {212 throw new TypeError('The `hooks` option must be an object');213 }210);214215 return {216 init: newHookValue(original, incomingHooks, 'init'),217 beforeRequest: newHookValue(original, incomingHooks, 'beforeRequest'),218 beforeRetry: newHookValue(original, incomingHooks, 'beforeRetry'),219 beforeError: newHookValue(original, incomingHooks, 'beforeError'),220 afterResponse: newHookValue(original, incomingHooks, 'afterResponse'),221 };222};223224export const deletedParametersSymbol = Symbol('deletedParameters');225226// `replaceOption()` can wrap a value at any depth of a deep-merged option, but a wrapper is only unwrapped where a227// merge actually runs, so a wrapper on a key with no parent value kept its `{value}` envelope. This resolves the
231 unmodified lines
modified:test/hooks.ts+68 added
6 unmodified lines
7 isNetworkError,8 isTimeoutError,9 isForceRetryError,10 TimeoutError,11 replaceOption,12} from '../source/index.js';13import {type Options, type NormalizedOptions} from '../source/types/options.js';14import {createHttpTestServer} from './helpers/create-http-test-server.js';15
7190 unmodified lines
7206 });72077208 t.true(cancelled);7209});72107211// `newHookValue` merged with `deepMerge`, which ignores sources that are neither arrays nor objects, so a single7212// function, a string or `null` was dropped without a word and the hook simply never ran.7213test('rejects a hook list that is not an array', t => {7214 for (const [key, value] of [7215 ['init', () => undefined],7216 ['beforeRequest', 'not a function'],7217 ['afterResponse', null],7218 ['beforeRetry', {}],7219 ['beforeError', 0],7220 ] as Array<[string, unknown]>) {7221 const hooks: Record<string, unknown> = {[key]: value};72227223 t.throws(() => {7224 void ky('https://example.com', {hooks: hooks as never});7225 }, {7226 instanceOf: TypeError,7227 message: `\`hooks.${key}\` must be an array`,7228 }, `${key}: ${JSON.stringify(value)}`);7229 }7230});72317232test('rejects `replaceOption()` around a non-array hook list', t => {7233 for (const value of [() => undefined, 42, {}] as unknown[]) {7234 t.throws(() => {7235 void ky('https://example.com', {hooks: {beforeRetry: replaceOption(value as never)}});7236 }, {7237 instanceOf: TypeError,7238 message: '`hooks.beforeRetry` must be an array',7239 });7240 }7241});72427243test('a single-function hook is reported instead of silently dropped', t => {7244 let ran = 0;7245 const hooks = {7246 beforeRequest: (() => {7247 ran++;7248 }) as never,7249 };72507251 const error = t.throws(() => {7252 void ky('https://example.com', {7253 retry: 0,7254 hooks,7255 fetch: async () => new Response('ok'),7256 });7257 });72587259 t.is(error?.message, '`hooks.beforeRequest` must be an array');7260 t.is(ran, 0);7261});72627263test('`hooks` that is not an object reports a clear error', t => {7264 for (const hooks of ['none', 42, true] as unknown[]) {7265 t.throws(() => {7266 void ky('https://example.com', {hooks: hooks as never});7267 }, {7268 instanceOf: TypeError,7269 message: 'The `hooks` option must be an object',7270 }, `hooks: ${JSON.stringify(hooks)}`);7271 }7272});72737274test('`hooks: null` selects the default', async t => {7275 t.is(await ky('https://example.com', {hooks: null as never, fetch: async () => new Response('ok')}).text(), 'ok');7276});