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

Implement attachment download #951

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
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
29 changes: 28 additions & 1 deletion docs/attachments/attachment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ paths:
schema:
type: boolean
required: false
description: If true will include in response attachments that have isDuplicate set to true.
description: If true will include in response attachments that have isDuplicate set to true.
responses:
200:
description: OK
Expand Down Expand Up @@ -134,6 +134,33 @@ paths:
code: UNAUTHORIZED
message: The requested URL requires user authorization.
/attachments/{id}:
get:
security:
- cookieAuth: []
tags:
- Attachments
summary: Get attachment blob by ID
description: Creates a blob for attachment with the specified ID.
produces:
- application/octet-stream
parameters:
- name: id
in: path
required: true
description: ID of the attachment
type: string
responses:
'200':
description: Successfully downloaded the blob file.
content:
application/octet-stream:
schema:
type: string
format: binary
'404':
description: Blob not found for the given ID.
'500':
description: Error occurred during blob download.
patch:
security:
- cookieAuth: []
Expand Down
9 changes: 8 additions & 1 deletion src/controllers/attachment.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,16 @@ const deleteAttachment = async (req, res) => {
res.status(204).end()
}

const downloadAttachment = async (req, res) => {
const { id } = req.params
const attachment = await attachmentService.downloadAttachment(id, res)
res.status(201).json(attachment)
}

module.exports = {
getAttachments,
createAttachments,
updateAttachment,
deleteAttachment
deleteAttachment,
downloadAttachment
}
1 change: 1 addition & 0 deletions src/routes/attachment.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {
const params = [{ model: Attachment, idName: 'id' }]

router.use(authMiddleware)
router.get('/:id', asyncWrapper(attachmentController.downloadAttachment))
router.use(restrictTo(TUTOR))
router.param('id', idValidation)

Expand Down
13 changes: 13 additions & 0 deletions src/services/attachment.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,19 @@ const attachmentService = {
}

await Attachment.findByIdAndRemove(id).exec()
},

downloadAttachment: async (id, res) => {
const attachment = await Attachment.findById(id).exec()

if (!attachment) {
throw createError(404, DOCUMENT_NOT_FOUND('Attachment'))
}

res.setHeader('Content-Disposition', `attachment; filename="${attachment.fileName}"`)
res.setHeader('Content-Type', 'application/octet-stream')

return await uploadService.downloadFile(attachment.link, ATTACHMENT, res)
}
}

Expand Down
14 changes: 14 additions & 0 deletions src/services/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ const uploadService = {
resolve(res)
})
).catch((e) => e.message)
},

downloadFile: (fileName, containerName, res) => {
blobService = azureStorage.createBlobService(STORAGE_ACCOUNT, ACCESS_KEY, AZURE_HOST)

return new Promise((resolve, reject) => {
blobService.getBlobToStream(containerName, fileName, res, (err) => {
if (err) {
reject(new Error('Download error'))
} else {
resolve()
}
})
})
}
}

Expand Down
61 changes: 61 additions & 0 deletions src/test/integration/controllers/attachments.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { UNAUTHORIZED, FORBIDDEN, DOCUMENT_NOT_FOUND } = require('~/consts/errors
const TokenService = require('~/services/token')
const Attachment = require('~/models/attachment')
const uploadService = require('~/services/upload')
const attachmentService = require('~/services/attachment')

const {
enums: { RESOURCES_TYPES_ENUM }
Expand Down Expand Up @@ -298,3 +299,63 @@ describe('Attachments controller', () => {
})
})
})

describe('downloadAttachment', () => {
jest.mock('~/models/attachment')
jest.mock('~/services/upload')
const ATTACHMENT = 'attachment'

afterEach(() => {
jest.clearAllMocks()
})

beforeAll(() => {
uploadService.downloadFile = jest.fn()
})

it('should download the attachment successfully when it exists', async () => {
const attachmentId = 'testId'
const attachment = {
_id: attachmentId,
fileName: 'testFile.txt',
link: 'https://example.com/testFile.txt'
}

const responseMock = {
setHeader: jest.fn()
}

jest.spyOn(Attachment, 'findById').mockReturnValue({
exec: jest.fn().mockResolvedValue(attachment)
})
uploadService.downloadFile.mockResolvedValue()

await expect(attachmentService.downloadAttachment(attachmentId, responseMock)).resolves.toBeUndefined()

expect(Attachment.findById).toHaveBeenCalledWith(attachmentId)
expect(responseMock.setHeader).toHaveBeenCalledWith(
'Content-Disposition',
`attachment; filename="${attachment.fileName}"`
)
expect(responseMock.setHeader).toHaveBeenCalledWith('Content-Type', 'application/octet-stream')
expect(uploadService.downloadFile).toHaveBeenCalledWith(attachment.link, ATTACHMENT, responseMock)
})

it('should throw a 404 error if the attachment is not found', async () => {
const attachmentId = 'nonExistentId'
const responseMock = {
setHeader: jest.fn()
}

jest.spyOn(Attachment, 'findById').mockReturnValue({
exec: jest.fn().mockResolvedValue(null)
})

await expect(attachmentService.downloadAttachment(attachmentId, responseMock)).rejects.toThrow(
'Attachment with the specified IDs were not found.'
)
expect(Attachment.findById).toHaveBeenCalledWith(attachmentId)
expect(responseMock.setHeader).not.toHaveBeenCalled()
expect(uploadService.downloadFile).not.toHaveBeenCalled()
})
})
50 changes: 49 additions & 1 deletion src/test/unit/services/upload.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const getBlobPropertiesStatusWithError = (container, blobName, cb) => {
}

const file = {
buffer: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD...',
buffer: 'data:image/jpegbase64,/9j/4AAQSkZJRgABAgAAAQABAAD...',
name: 'example.jpg',
newName: 'exampleName.jpg'
}
Expand Down Expand Up @@ -122,3 +122,51 @@ describe('uploadService', () => {
}
})
})

describe('downloadFile', () => {
jest.mock('azure-storage', () => ({
createBlobService: jest.fn()
}))

let blobServiceMock

beforeEach(() => {
blobServiceMock = {
getBlobToStream: jest.fn()
}
azureStorage.createBlobService.mockReturnValue(blobServiceMock)
})

afterEach(() => {
jest.clearAllMocks()
})

it('should resolve if the blob is downloaded successfully', async () => {
const fileName = 'testFile.txt'
const containerName = 'test-container'
const responseMock = jest.fn()

blobServiceMock.getBlobToStream.mockImplementation((container, file, res, callback) => {
callback(null)
})

await expect(uploadService.downloadFile(fileName, containerName, responseMock)).resolves.toBeUndefined()
expect(azureStorage.createBlobService).toHaveBeenCalled()
expect(blobServiceMock.getBlobToStream).toHaveBeenCalled()
})

it('should reject if there is an error downloading the blob', async () => {
const fileName = 'testFile.txt'
const containerName = 'test-container'
const responseMock = jest.fn()
const error = new Error('Download error')

blobServiceMock.getBlobToStream.mockImplementation((container, file, res, callback) => {
callback(error)
})

await expect(uploadService.downloadFile(fileName, containerName, responseMock)).rejects.toThrow('Download error')
expect(azureStorage.createBlobService).toHaveBeenCalled()
expect(blobServiceMock.getBlobToStream).toHaveBeenCalled()
})
})
Loading