76 lines
2.2 KiB
JavaScript
76 lines
2.2 KiB
JavaScript
const UserError = require('vn-loopback/util/user-error');
|
|
const fs = require('fs-extra');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethodCtx('downloadFile', {
|
|
description: 'Download a document',
|
|
accessType: 'READ',
|
|
accepts: [
|
|
{
|
|
arg: 'id',
|
|
type: 'String',
|
|
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: {
|
|
path: `/:id/downloadFile`,
|
|
verb: 'GET'
|
|
}
|
|
});
|
|
|
|
Self.downloadFile = async function(ctx, id) {
|
|
const env = process.env.NODE_ENV;
|
|
const models = Self.app.models;
|
|
const dms = await Self.findById(id, {
|
|
include: {
|
|
relation: 'dmsType',
|
|
scope: {
|
|
fields: ['path', 'readRoleFk'],
|
|
include: {
|
|
relation: 'readRole'
|
|
}
|
|
}
|
|
}
|
|
});
|
|
|
|
const hasReadRole = await models.DmsType.hasReadRole(ctx, dms.dmsTypeFk);
|
|
if (!hasReadRole)
|
|
throw new UserError(`You don't have enough privileges`);
|
|
|
|
if (env && env != 'development') {
|
|
const path = `/${dms.companyFk}/${dms.dmsType().path}/${dms.file}`;
|
|
file = {
|
|
path: `/var/lib/salix/dms/${path}`,
|
|
contentType: 'application/octet-stream',
|
|
name: dms.file
|
|
};
|
|
} else {
|
|
file = {
|
|
path: `${process.cwd()}/README.md`,
|
|
contentType: 'text/plain',
|
|
name: `README.md`
|
|
};
|
|
}
|
|
|
|
await fs.access(file.path);
|
|
let stream = fs.createReadStream(file.path);
|
|
return [stream, file.contentType, `filename="${file.name}"`];
|
|
};
|
|
};
|