Skip to content

Commit

Permalink
http post download file
Browse files Browse the repository at this point in the history
  • Loading branch information
Paola Nicosia committed Nov 3, 2022
1 parent 0dd5f2d commit 45cdd67
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/utils/__tests__/http-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,31 @@ describe('http-client tests', () => {
expect(await data?.text()).toStrictEqual('ok')
})

it('should fetch a post method with file download', async () => {
const body = {key: 'value'}
fetchMock.mockOnceIf(/\/$/, () => {
return Promise.resolve({
status: 200,
body: 'text',
headers: {
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename=file.csv'
}
})
})

const {
headers, status
} = await createFetchHttpClient.bind<() => HttpClientInstance>(support)().post('/', body, {
downloadAsFile: true
})

expect(downloadFile).toBeCalled()
expect(status).toBe(200)
expect(headers.get('Content-Type')).toStrictEqual('text/plain')
expect(headers.get('Content-Disposition')).toStrictEqual('attachment; filename=file.csv')
})

it('should fetch post method with text response applying a transform', async () => {
const body = {key: 'value'}
const modBody = {key: 'value1'}
Expand Down
16 changes: 16 additions & 0 deletions src/utils/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,22 @@ const withBody = (method: 'POST' | 'DELETE' | 'PUT') =>
return fetchPromise
}

if (method === 'POST' && fetchConfig.downloadAsFile) {
return await fetchPromise.then(response => {
const filename = response.headers.get('Content-Disposition')?.match(/filename=([^;]+)/)?.[1]

return Promise.all([
Promise.resolve(response),
Promise.resolve(filename),
response.blob()
])
})
.then(([response, filename, blob]) => {
downloadFile.bind(this)(blob, filename)
return response
})
}

return await processResponse(fetchPromise, outputTransform)
} catch (err) {
return Promise.reject(defaultErrorHandler(err))
Expand Down

0 comments on commit 45cdd67

Please sign in to comment.