Skip to content

Commit 9bd9ca5

Browse files
committed
add file download endpoint
1 parent fbf1761 commit 9bd9ca5

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

src/permissions/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,6 @@ module.exports = () => {
1919
Authorizer.setPolicy('project.addAttachment', projectEdit);
2020
Authorizer.setPolicy('project.updateAttachment', projectEdit);
2121
Authorizer.setPolicy('project.removeAttachment', projectEdit);
22+
Authorizer.setPolicy('project.downloadAttachment', projectView);
2223
Authorizer.setPolicy('project.updateMember', projectEdit);
2324
};

src/routes/attachments/download.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
2+
import _ from 'lodash';
3+
import { middleware as tcMiddleware } from 'tc-core-library-js';
4+
import models from '../../models';
5+
import util from '../../util';
6+
7+
/**
8+
* API to download a project attachment.
9+
*
10+
*/
11+
12+
const permissions = tcMiddleware.permissions;
13+
14+
module.exports = [
15+
permissions('project.downloadAttachment'),
16+
(req, res, next) => {
17+
const projectId = _.parseInt(req.params.projectId);
18+
const attachmentId = _.parseInt(req.params.id);
19+
20+
models.ProjectAttachment.findOne(
21+
{
22+
where: {
23+
id: attachmentId,
24+
projectId,
25+
},
26+
})
27+
.then((attachment) => {
28+
if (!attachment) {
29+
const err = new Error('Record not found');
30+
err.status = 404;
31+
return Promise.reject(err);
32+
}
33+
return util.getFileDownloadUrl(req, attachment.filePath);
34+
})
35+
.then((result) => {
36+
const url = result[1];
37+
res.status(200).json(util.wrapResponse(req.id, { url }));
38+
})
39+
.catch((error) => {
40+
req.log.error('Error fetching attachment', error);
41+
const rerr = error;
42+
rerr.status = rerr.status || 500;
43+
next(rerr);
44+
});
45+
},
46+
];

src/routes/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ router.route('/v4/projects/:projectId(\\d+)/members/:id(\\d+)')
4848
router.route('/v4/projects/:projectId(\\d+)/attachments')
4949
.post(require('./attachments/create'));
5050
router.route('/v4/projects/:projectId(\\d+)/attachments/:id(\\d+)')
51+
.get(require('./attachments/download'))
5152
.patch(require('./attachments/update'))
5253
.delete(require('./attachments/delete'));
5354

0 commit comments

Comments
 (0)