Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions create-fetchival.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,27 @@ function query(params) {
.join('&')}`
}

const prevenJsonStringifyContentTypes = new Set(['application/x-sentry-envelope'])

function createFetchival({ fetch }) {
async function _fetch(method, url, opts, data) {
// Unlike fetchival, don't silently ignore and override
if (opts.body) throw new Error('unexpected pre-set body option')

const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
...opts.headers,
}
// Allows some consumers to avoid JSON.stringify for their vendor-specific content types.
const shouldStringify = !prevenJsonStringifyContentTypes.has(headers['Content-Type'])

// Unlike fetchival, don't pollute the opts object we were given
const res = await fetchival.fetch(url, {
...opts,
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...opts.headers,
},
...(data ? { body: JSON.stringify(data) } : {}),
headers,
...(data ? { body: shouldStringify ? JSON.stringify(data) : data } : {}),
})

if (res.status >= 200 && res.status < 300) {
Expand Down
44 changes: 44 additions & 0 deletions test/create-fetchival.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,48 @@ tape('createFetchival', (t) => {
t.equals(err.message, 'Couldnt establish connection')
}
})

t.test('does not stringify body for specific Conent-Type headers', async (t) => {
let capturedOpts
const formData = 'name=John&age=30'
const fetch = async (url, opts) => {
capturedOpts = opts
return { status: 200, json: async () => ({ success: true }) }
}

const fetchival = createFetchival({ fetch })

await fetchival('https://example.com')('api', {
headers: {
'Content-Type': 'application/x-sentry-envelope',
},
}).post(formData)

t.equals(
capturedOpts.body,
formData,
'body should not be stringified for non-JSON content type'
)
t.equals(capturedOpts.headers['Content-Type'], 'application/x-sentry-envelope')
})

t.test('applies JSON.stringify to body by default', async (t) => {
let capturedOpts
const formData = 'name=John&age=30'
const fetch = async (url, opts) => {
capturedOpts = opts
return { status: 200, json: async () => ({ success: true }) }
}

const fetchival = createFetchival({ fetch })

await fetchival('https://example.com')('api').post(formData)

t.equals(
capturedOpts.body,
JSON.stringify(formData),
'body should not be stringified for non-JSON content type'
)
t.equals(capturedOpts.headers['Content-Type'], 'application/json')
})
})