salix/back/methods/dms/downloadFile.js

63 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-05-01 16:49:39 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethodCtx('downloadFile', {
2019-05-01 16:49:39 +00:00
description: 'Download a document',
accessType: 'READ',
accepts: [
{
arg: 'id',
type: 'Number',
2019-07-15 13:05:54 +00:00
description: 'Document id',
2019-05-01 16:49:39 +00:00
http: {source: 'path'}
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: `/:id/downloadFile`,
2019-05-01 16:49:39 +00:00
verb: 'GET'
}
});
Self.downloadFile = async function(ctx, id) {
const storageConnector = Self.app.dataSources.storage.connector;
const models = Self.app.models;
const dms = await Self.findById(id);
2019-05-01 16:49:39 +00:00
const hasReadRole = await models.DmsType.hasReadRole(ctx, dms.dmsTypeFk);
if (!hasReadRole)
2019-05-01 16:49:39 +00:00
throw new UserError(`You don't have enough privileges`);
2019-07-16 11:37:25 +00:00
const pathHash = storageConnector.getPathHash(dms.id);
try {
await models.Container.getFile(pathHash, dms.file);
} catch (e) {
if (e.code != 'ENOENT')
throw e;
const error = new UserError(`File doesn't exists`);
error.statusCode = 404;
throw error;
2019-05-01 16:49:39 +00:00
}
2019-07-16 11:37:25 +00:00
const stream = models.Container.downloadStream(pathHash, dms.file);
2019-07-16 11:37:25 +00:00
return [stream, dms.contentType, `filename="${dms.file}"`];
2019-05-01 16:49:39 +00:00
};
};