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

71 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-10-24 12:20:09 +00:00
const JSZip = require('jszip');
const fs = require('fs-extra');
const UserError = require('vn-loopback/util/user-error');
2022-10-24 12:20:09 +00:00
module.exports = Self => {
Self.remoteMethodCtx('downloadZip', {
description: 'Download a zip file with multiple invoices pdfs',
accessType: 'READ',
accepts: [
{
arg: 'ids',
type: 'string',
description: 'The invoices ids',
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
}, {
arg: 'Content-Type',
type: 'string',
http: {target: 'header'}
}, {
arg: 'Content-Disposition',
type: 'string',
http: {target: 'header'}
2022-10-24 12:20:09 +00:00
}
],
http: {
path: '/downloadZip',
verb: 'GET'
},
accessScopes: ['DEFAULT', 'read:multimedia']
2022-10-24 12:20:09 +00:00
});
Self.downloadZip = async function(ctx, ids, options) {
const models = Self.app.models;
const myOptions = {};
const zip = new JSZip();
2022-10-24 12:20:09 +00:00
if (typeof options == 'object')
Object.assign(myOptions, options);
2022-12-20 09:40:39 +00:00
const zipConfig = await models.ZipConfig.findOne(null, myOptions);
2022-10-24 12:20:09 +00:00
let totalSize = 0;
ids = ids.split(',');
2022-10-24 12:20:09 +00:00
for (let id of ids) {
if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large');
2022-10-24 12:20:09 +00:00
const invoiceOutPdf = await models.InvoiceOut.download(ctx, id, myOptions);
const fileName = extractFileName(invoiceOutPdf[2]);
const body = invoiceOutPdf[0];
const sizeInBytes = (await fs.promises.stat(body.path)).size;
const sizeInMegabytes = sizeInBytes / (1024 * 1024);
totalSize += sizeInMegabytes;
zip.file(fileName, body);
}
const stream = zip.generateNodeStream({streamFiles: true});
return [stream, 'application/zip', `filename="download.zip"`];
2022-10-24 12:20:09 +00:00
};
function extractFileName(str) {
const matches = str.match(/"(.*?)"/);
return matches ? matches[1] : str;
}
};