const fs = require('fs-extra'); module.exports = Self => { Self.remoteMethod('download', { description: 'Download an invoice PDF', accessType: 'READ', accepts: [ { arg: 'id', type: 'String', description: 'The invoice 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(id) { let file; let env = process.env.NODE_ENV; let [invoice] = await Self.rawSql(`SELECT hedera.invoiceGetPath(?) path`, [id]); if (env && env != 'development') { file = { path: `/var/lib/salix/pdfs/${invoice.path}`, contentType: 'application/pdf', name: `${id}.pdf` }; } 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, `attachment; filename="${file.name}"`]; }; };