salix/modules/invoiceOut/back/methods/invoiceOut/download.js

68 lines
1.9 KiB
JavaScript

const fs = require('fs-extra');
const path = require('path');
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, options) {
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const invoiceOut = await models.InvoiceOut.findById(id, null, myOptions);
const created = invoiceOut.created;
const year = created.getFullYear().toString();
const month = created.getMonth().toString();
const day = created.getDate().toString();
const container = await models.InvoiceContainer.container(year);
const rootPath = container.client.root;
const src = path.join(rootPath, year, month, day);
const fileName = `${invoiceOut.ref}.pdf`;
const fileSrc = path.join(src, fileName);
const file = {
path: fileSrc,
contentType: 'application/pdf',
name: `${id}.pdf`
};
await fs.access(file.path);
let stream = fs.createReadStream(file.path);
return [stream, file.contentType, `filename="${file.name}"`];
};
};