Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: CORS issue with downloadFile helper #38

Merged
merged 2 commits into from
Jan 27, 2025
Merged
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@chatwoot/utils",
"version": "0.0.31",
"version": "0.0.32",
"description": "Chatwoot utils",
"private": false,
"license": "MIT",
Expand Down
17 changes: 14 additions & 3 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,21 @@ export const downloadFile = async ({
type,
extension = null,
}: DownloadFileOptions): Promise<void> => {
if (!url || !type) return;
if (!url || !type) {
throw new Error('Invalid download parameters');
}

try {
const response = await fetch(url);
const response = await fetch(url, {
method: 'GET',
credentials: 'omit',
mode: 'cors',
});

if (!response.ok) {
throw new Error(`Download failed: ${response.status}`);
}

const blobData = await response.blob();

const contentType = response.headers.get('content-type');
Expand All @@ -240,6 +251,6 @@ export const downloadFile = async ({
link.remove();
URL.revokeObjectURL(blobUrl);
} catch (error) {
console.warn('Download failed:', error);
throw error instanceof Error ? error : new Error('Download failed');
}
};
46 changes: 34 additions & 12 deletions test/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ describe('downloadFile', () => {
remove: jest.fn(),
href: '',
download: '',
style: '',
};
document.createElement = jest.fn().mockReturnValue(mockDOMElement);
document.body.append = jest.fn();
Expand All @@ -159,7 +160,7 @@ describe('downloadFile', () => {
afterEach(() => jest.clearAllMocks());

describe('successful downloads', () => {
it('should download PDF file', async () => {
it('should download PDF file with correct fetch options', async () => {
const blob = new Blob(['test'], { type: 'application/pdf' });
mockFetch.mockResolvedValueOnce({
ok: true,
Expand All @@ -173,12 +174,16 @@ describe('downloadFile', () => {
extension: 'pdf',
});

expect(mockFetch).toHaveBeenCalledWith('test.com/doc.pdf');
expect(mockFetch).toHaveBeenCalledWith('test.com/doc.pdf', {
method: 'GET',
credentials: 'omit',
mode: 'cors',
});
expect(mockCreateObjectURL).toHaveBeenCalledWith(blob);
expect(mockDOMElement.click).toHaveBeenCalled();
});

it('should download image file with content disposition', async () => {
it('should download file with content disposition filename', async () => {
const blob = new Blob(['test'], { type: 'image/png' });
mockFetch.mockResolvedValueOnce({
ok: true,
Expand All @@ -196,24 +201,41 @@ describe('downloadFile', () => {
});

expect(mockDOMElement.download).toBe('test.png');
expect(document.body.append).toHaveBeenCalled();
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-url');
});
});

describe('error handling', () => {
it('should skip if url or type missing', async () => {
await downloadFile({ url: '', type: 'pdf' });
it('should throw error if url or type missing', async () => {
await expect(downloadFile({ url: '', type: 'pdf' })).rejects.toThrow(
'Invalid download parameters'
);

await expect(downloadFile({ url: 'test.com', type: '' })).rejects.toThrow(
'Invalid download parameters'
);

expect(mockFetch).not.toHaveBeenCalled();
});

it('should handle network errors', async () => {
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
it('should throw error on failed response', async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404,
});

await expect(
downloadFile({ url: 'test.com/file', type: 'pdf' })
).rejects.toThrow('Download failed: 404');
});

it('should throw error on network failure', async () => {
mockFetch.mockRejectedValueOnce(new Error('Network error'));

await downloadFile({ url: 'test.com/file', type: 'pdf' });
expect(consoleSpy).toHaveBeenCalledWith(
'Download failed:',
expect.any(Error)
);
await expect(
downloadFile({ url: 'test.com/file', type: 'pdf' })
).rejects.toThrow('Network error');
});
});
});
Loading