Estoy definiendo mi método remoto de loopback de la siguiente manera
Visitor.remoteMethod('getVisitorsPDF', { description: 'Get visitors list in PDF file', accepts: [ { arg: 'res', type: 'object', http: { source: 'res' } }, { arg: 'dateInStart', type: 'string' }, { arg: 'dateInEnd', type: 'string' }, { arg: 'employeeSiteId', type: 'string' }, { arg: 'name', type: 'string' }, { arg: 'visitorCompany', type: 'string' }, { arg: 'employeeName', type: 'string' }, { arg: 'typeId', type: 'number' }, { arg: 'shift', type: 'number' } ], returns: {}, http: { path: '/getpdf', verb: 'get' } });y su implementación es la siguiente:
Visitor.app.models.user.testAccess(res).then( (current) => { .... res.set('Content-Type', 'application/pdf'); res.set('Content-Disposition', 'attachment;filename="visitors.pdf"'); ... Visitor._getVisitors(query, current).then( (visitors) => { let visitorsFiltered = visitors.filter((v) => { if (!v.tztimeIn) return v; let d = v.timeIn + v.tztimeIn * 60000; if (dStart < d && d < dEnd) return v; }); Visitor._getVisitorsPDF(visitorsFiltered) .then(result => { res.send(result); }, ); }, ); } ) };Y la función que está generando pdf es la siguiente:
Visitor._getVisitorsPDF = async function (visitors) { ... const rows = tempData; const doc = new jsPDF(); doc.autoTable(columns, rows); doc.save('visitors.pdf'); }¿Cómo devolver este documento como respuesta de solicitud/pdf? estoy atrapado aquí
He usado node-html-pdf para generar y enviar archivos PDF. Tiene un método incorporado para devolver un búfer.
En su código, doc.save('file') guarda el archivo en el pwd.
Luego, podría usar fs para leer el archivo guardado de forma asincrónica y luego almacenarlo en el cliente.
import stream from "stream"; ... fs.readFile('file', (err, fileBuffer) => { if (err) throw err; // console.log(fileBuffer); let encodedBuffer = Buffer.from(JSON.stringify(fileBuffer)); // create a stream to the receiver let readStream = new stream.PassThrough(); readStream.end(encodedBuffer); res.set("Content-disposition", "attachment; filename=" + filename); res.set("Content-Type", "application/pdf"); readStream.pipe(res); });Donde res el objeto de respuesta regular (de tipo Solicitud en @loopback/rest), puede hacer:
res.download(result)En vez de
res.send(result).