From 82cdd66ad8b6dfb6ccf9f4adbc0a67cda1aeb967 Mon Sep 17 00:00:00 2001 From: Abigail Young Date: Fri, 23 Feb 2024 14:43:55 -0800 Subject: [PATCH] fix code to account for query params on end of asset url in s3 --- src/helpers/openDocumentLink.test.ts | 14 ++++++++++---- src/helpers/openDocumentLink.ts | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/helpers/openDocumentLink.test.ts b/src/helpers/openDocumentLink.test.ts index 509f19f36..16699be0f 100644 --- a/src/helpers/openDocumentLink.test.ts +++ b/src/helpers/openDocumentLink.test.ts @@ -18,10 +18,10 @@ URL.revokeObjectURL = mockRevokeObjectURL const mockWindowOpen = jest.fn() window.open = mockWindowOpen -describe('isPdf', () => { +describe('openDocumentLink', () => { Object.entries(mimeTypes).forEach(([extension, type]) => { - test('returns correct type if url ends with extension', () => { - const fileName = `https://www.google.com/test.${extension}` + test('returns correct type if url is hosted on s3', () => { + const fileName = `https://www.google.com/test.${extension}?queryparamsands3things` expect(getMimeType(fileName)).toBe(type) }) }) @@ -31,11 +31,17 @@ describe('isPdf', () => { 'application/octet-stream' ) }) + + test('returns correct type if url ends with extension', () => { + expect(getMimeType('https://www.google.com/test.pdf')).toBe( + 'application/pdf' + ) + }) }) describe('handleOpenPdfLink', () => { test('opens a new window if the url is a pdf', async () => { - const pdfString = 'https://www.google.com/test.pdf' + const pdfString = 'https://www.google.com/test.pdf?queryparamsands3things' await openFileInNewTab(pdfString) expect(axios.get).toHaveBeenCalled() expect(mockCreateObjectURL).toHaveBeenCalled() diff --git a/src/helpers/openDocumentLink.ts b/src/helpers/openDocumentLink.ts index b2f245fba..3aafbb60d 100644 --- a/src/helpers/openDocumentLink.ts +++ b/src/helpers/openDocumentLink.ts @@ -20,8 +20,22 @@ export const mimeTypes: Record = { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // Add more mappings as needed } + +export const extractExtensionFromUrl = (url: string): string | null => { + // Remove query parameters if there are any + const baseUrl = url.split('?')[0].toLowerCase() + const extensions = Object.keys(mimeTypes) + + for (const extension of extensions) { + if (baseUrl.endsWith(`.${extension}`)) { + return extension + } + } + return null +} + export const getMimeType = (url: string): string => { - const extension = url.split('.').pop()?.toLowerCase() + const extension = extractExtensionFromUrl(url) return mimeTypes[extension || ''] || 'application/octet-stream' // Default MIME type } // Function to open files in a new tab with TypeScript annotations