const UserError = require('vn-loopback/util/user-error'); const fs = require('fs-extra'); module.exports = Self => { Self.remoteMethodCtx('download', { 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/download`, verb: 'GET' } }); Self.download = async function(ctx, id) { const userId = ctx.req.accessToken.userId; const env = process.env.NODE_ENV; const document = await Self.findById(id, { include: { relation: 'dmsType', scope: { fields: ['path', 'readRoleFk'], include: { relation: 'readRole' } } } }); const readRole = document.dmsType().readRole().name; const hasRequiredRole = await Self.app.models.Account.hasRole(userId, readRole); if (!hasRequiredRole) throw new UserError(`You don't have enough privileges`); if (env && env != 'development') { const path = `/${document.companyFk}/${document.dmsType().path}/${document.file}`; file = { path: `/var/lib/salix/dms/${path}`, contentType: 'application/octet-stream', name: document.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}"`]; }; };