const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('downloadFile', { description: 'Download a document', accessType: 'READ', accepts: [ { arg: 'id', type: 'Number', description: '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 storageConnector = Self.app.dataSources.storage.connector; const models = Self.app.models; const dms = await Self.findById(id); 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 pathHash = storageConnector.getPathHash(dms.id); file = { contentType: dms.contentType, container: pathHash, name: dms.file }; } else { file = { contentType: 'text/plain', container: 'temp', name: `file.txt` }; } const stream = await models.Container.downloadStream(file.container, file.name); return [stream, file.contentType, `filename="${file.name}"`]; }; };