Skip to content

Commit

Permalink
fix: default fetch implementation called on non Window object (#88)
Browse files Browse the repository at this point in the history
* fix: default fetch implementation called on non Window object
  • Loading branch information
Alan Shaw authored Sep 9, 2022
1 parent 37f1d66 commit 66a22ee
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
13 changes: 9 additions & 4 deletions packages/transport/src/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,16 @@ import * as API from '@ucanto/interface'
* @param {string} [options.method]
* @returns {API.Channel<T>}
*/
export const open = ({ url, method = 'POST', fetch = globalThis.fetch }) => {
export const open = ({ url, method = 'POST', fetch }) => {
/* c8 ignore next 9 */
if (!fetch) {
throw new TypeError(
`ucanto HTTP transport got undefined \`fetch\`. Try passing in a \`fetch\` implementation explicitly.`
)
if (typeof globalThis.fetch !== 'undefined') {
fetch = globalThis.fetch.bind(globalThis)
} else {
throw new TypeError(
`ucanto HTTP transport got undefined \`fetch\`. Try passing in a \`fetch\` implementation explicitly.`
)
}
}
return new Channel({ url, method, fetch })
}
Expand Down
31 changes: 16 additions & 15 deletions packages/transport/test/https.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ if (!globalThis.fetch) {
})
}

test('faild request', async () => {
test('failed request', async () => {
const channel = HTTP.open({
url: new URL('https://ucan.xyz/'),
fetch: async (url, init) => {
Expand Down Expand Up @@ -68,17 +68,18 @@ test('faild request', async () => {
}
})

test('fail request without fetch impl', async () => {
try {
const channel = HTTP.open({
url: new URL('https://ucan.xyz/'),
// @ts-ignore
fetch: null,
})
assert.fail('expected to throw')
} catch (reason) {
const error = /** @type {any} */ (reason)
assert.match(String(error), /TypeError/)
assert.equal(error.name, 'TypeError')
}
})
// Tests for environments that DO NOT have a globalThis.fetch implementation.
if (typeof globalThis.fetch === 'undefined') {
test('fail request without fetch impl', async () => {
try {
const channel = HTTP.open({
url: new URL('https://ucan.xyz/')
})
assert.fail('expected to throw')
} catch (reason) {
const error = /** @type {any} */ (reason)
assert.match(String(error), /TypeError/)
assert.equal(error.name, 'TypeError')
}
})
}

0 comments on commit 66a22ee

Please sign in to comment.