Skip to content

Commit aa71e81

Browse files
authoredMay 9, 2022
fix: make defaults chaining actually work (#144)
The README says: > A defaulted `fetch` will also have a `.defaults()` method, so they can > be chained. But this didn't really work, because while the `defaults` method was placed on the `defaulted` fetch, a chained defaulted fetch would just call the original fetch function directly instead of the intermediate function. This PR makes chaining actually work and adds a test. Also, it fixes the previous test, which wasn't actually verifying that the correct request headers were received because it used the nock API incorrectly: the option is `reqheaders` not `reqHeaders`.
1 parent ac55965 commit aa71e81

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed
 

‎lib/index.js

+4-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const makeFetchHappen = (url, opts) => {
1010
return fetch(request, options)
1111
}
1212

13-
makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}) => {
13+
makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => {
1414
if (typeof defaultUrl === 'object') {
1515
defaultOptions = defaultUrl
1616
defaultUrl = null
@@ -26,10 +26,11 @@ makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}) => {
2626
...options.headers,
2727
},
2828
}
29-
return makeFetchHappen(finalUrl, finalOptions)
29+
return wrappedFetch(finalUrl, finalOptions)
3030
}
3131

32-
defaultedFetch.defaults = makeFetchHappen.defaults
32+
defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) =>
33+
makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch)
3334
return defaultedFetch
3435
}
3536

‎test/defaults.js

+25-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ t.test('can set default url', async (t) => {
2121

2222
t.test('allows default headers', async (t) => {
2323
const srv = nock('http://localhost', {
24-
reqHeaders: {
24+
reqheaders: {
2525
'x-foo': 'bar',
2626
'x-bar': 'baz',
2727
},
@@ -40,3 +40,27 @@ t.test('allows default headers', async (t) => {
4040
t.same(buf, Buffer.from('success'), 'got body')
4141
t.ok(srv.isDone())
4242
})
43+
44+
t.test('layering default headers works', async (t) => {
45+
const srv = nock('http://localhost', {
46+
reqheaders: {
47+
'x-foo': 'bar',
48+
'x-bar': 'baz',
49+
'x-another': 'yep',
50+
},
51+
})
52+
.get('/test')
53+
.reply(200, 'success')
54+
55+
const defaultedFetch1 = fetch.defaults({ headers: { 'x-foo': 'bar' } })
56+
const defaultedFetch2 = defaultedFetch1.defaults({ headers: { 'x-bar': 'baz' } })
57+
const res = await defaultedFetch2('http://localhost/test', {
58+
headers: {
59+
'x-another': 'yep',
60+
},
61+
})
62+
t.equal(res.status, 200, 'got success')
63+
const buf = await res.buffer()
64+
t.same(buf, Buffer.from('success'), 'got body')
65+
t.ok(srv.isDone())
66+
})

0 commit comments

Comments
 (0)
Please sign in to comment.