Skip to content

Commit

Permalink
fix: make defaults chaining actually work (#144)
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
glasser authored May 9, 2022
1 parent ac55965 commit aa71e81
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
7 changes: 4 additions & 3 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const makeFetchHappen = (url, opts) => {
return fetch(request, options)
}

makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}) => {
makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}, wrappedFetch = makeFetchHappen) => {
if (typeof defaultUrl === 'object') {
defaultOptions = defaultUrl
defaultUrl = null
Expand All @@ -26,10 +26,11 @@ makeFetchHappen.defaults = (defaultUrl, defaultOptions = {}) => {
...options.headers,
},
}
return makeFetchHappen(finalUrl, finalOptions)
return wrappedFetch(finalUrl, finalOptions)
}

defaultedFetch.defaults = makeFetchHappen.defaults
defaultedFetch.defaults = (defaultUrl1, defaultOptions1 = {}) =>
makeFetchHappen.defaults(defaultUrl1, defaultOptions1, defaultedFetch)
return defaultedFetch
}

Expand Down
26 changes: 25 additions & 1 deletion test/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ t.test('can set default url', async (t) => {

t.test('allows default headers', async (t) => {
const srv = nock('http://localhost', {
reqHeaders: {
reqheaders: {
'x-foo': 'bar',
'x-bar': 'baz',
},
Expand All @@ -40,3 +40,27 @@ t.test('allows default headers', async (t) => {
t.same(buf, Buffer.from('success'), 'got body')
t.ok(srv.isDone())
})

t.test('layering default headers works', async (t) => {
const srv = nock('http://localhost', {
reqheaders: {
'x-foo': 'bar',
'x-bar': 'baz',
'x-another': 'yep',
},
})
.get('/test')
.reply(200, 'success')

const defaultedFetch1 = fetch.defaults({ headers: { 'x-foo': 'bar' } })
const defaultedFetch2 = defaultedFetch1.defaults({ headers: { 'x-bar': 'baz' } })
const res = await defaultedFetch2('http://localhost/test', {
headers: {
'x-another': 'yep',
},
})
t.equal(res.status, 200, 'got success')
const buf = await res.buffer()
t.same(buf, Buffer.from('success'), 'got body')
t.ok(srv.isDone())
})

0 comments on commit aa71e81

Please sign in to comment.