2019-05-01 16:49:39 +00:00
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
|
|
|
module.exports = Self => {
|
2019-06-06 11:59:11 +00:00
|
|
|
Self.remoteMethodCtx('downloadFile', {
|
2019-05-01 16:49:39 +00:00
|
|
|
description: 'Download a document',
|
|
|
|
accessType: 'READ',
|
|
|
|
accepts: [
|
|
|
|
{
|
|
|
|
arg: 'id',
|
2019-06-26 11:35:38 +00:00
|
|
|
type: 'Number',
|
2019-05-01 16:49:39 +00:00
|
|
|
description: 'The document id',
|
|
|
|
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: {
|
2019-06-06 11:59:11 +00:00
|
|
|
path: `/:id/downloadFile`,
|
2019-05-01 16:49:39 +00:00
|
|
|
verb: 'GET'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2019-06-06 11:59:11 +00:00
|
|
|
Self.downloadFile = async function(ctx, id) {
|
2019-05-01 16:49:39 +00:00
|
|
|
const env = process.env.NODE_ENV;
|
2019-06-20 05:46:30 +00:00
|
|
|
const storageConnector = Self.app.dataSources.storage.connector;
|
2019-06-06 11:59:11 +00:00
|
|
|
const models = Self.app.models;
|
2019-06-20 05:46:30 +00:00
|
|
|
const dms = await Self.findById(id);
|
2019-05-01 16:49:39 +00:00
|
|
|
|
2019-06-06 11:59:11 +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`);
|
|
|
|
|
|
|
|
if (env && env != 'development') {
|
2019-06-20 05:46:30 +00:00
|
|
|
const pathHash = storageConnector.getPathHash(dms.id);
|
2019-05-01 16:49:39 +00:00
|
|
|
file = {
|
2019-07-15 11:16:02 +00:00
|
|
|
contentType: dms.contentType,
|
2019-06-20 05:46:30 +00:00
|
|
|
container: pathHash,
|
2019-06-06 11:59:11 +00:00
|
|
|
name: dms.file
|
2019-05-01 16:49:39 +00:00
|
|
|
};
|
|
|
|
} else {
|
|
|
|
file = {
|
|
|
|
contentType: 'text/plain',
|
2019-06-20 05:46:30 +00:00
|
|
|
container: 'temp',
|
|
|
|
name: `file.txt`
|
2019-05-01 16:49:39 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-06-20 05:46:30 +00:00
|
|
|
const stream = await models.Container.downloadStream(file.container, file.name);
|
|
|
|
|
2019-07-15 12:52:41 +00:00
|
|
|
return [stream, file.contentType, `filename="${file.name}"`];
|
2019-05-01 16:49:39 +00:00
|
|
|
};
|
|
|
|
};
|