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

81 lines
2.3 KiB
JavaScript

const fs = require('fs-extra');
const path = require('path');
const isProduction = require('vn-loopback/server/boot/isProduction');
module.exports = Self => {
Self.remoteMethodCtx('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'
},
accessScopes: ['DEFAULT', 'read:multimedia']
});
Self.download = async function(ctx, id, options) {
const models = Self.app.models;
options = typeof options == 'object'
? Object.assign({}, options) : {};
const pdfFile = await Self.filePath(id, options);
const container = await models.InvoiceContainer.container(pdfFile.year);
const rootPath = container.client.root;
const file = {
path: path.join(rootPath, pdfFile.path, pdfFile.name),
contentType: 'application/pdf',
name: pdfFile.name
};
try {
await fs.access(file.path);
} catch (error) {
await Self.createPdf(ctx, id, options);
}
let stream = await fs.createReadStream(file.path);
// XXX: To prevent unhandled ENOENT error
// https://stackoverflow.com/questions/17136536/is-enoent-from-fs-createreadstream-uncatchable
stream.on('error', err => {
const e = new Error(err.message);
err.stack = e.stack;
console.error(err);
});
if (!isProduction()) {
try {
await fs.access(file.path);
} catch (error) {
stream = null;
}
}
return [stream, file.contentType, `filename="${pdfFile.name}"`];
};
};