Tôi đang sử dụng PDFMake (một biến thể của PDFKit
) để tạo tệp PDF trên Firebase Cloud Functions bằng trình kích hoạt cơ sở dữ liệu thời gian thực. Hàm này nhận tất cả dữ liệu có liên quan từ cơ sở dữ liệu và sau đó chuyển nó đến hàm được cho là tạo ra tệp PDF.Sử dụng lời hứa bằng PDFMake trên Chức năng đám mây của Firebase
Tất cả điều này được thực hiện bằng Lời hứa. Tất cả mọi thứ hoạt động tốt cho đến khi PDF thực sự được tạo ra.
Dưới đây là mã trong lắng nghe sự kiện chính của tôi:
exports.handler = (admin, event, storage) => {
const quotationData = event.data.val();
// We must return a Promise when performing async tasks inside Functions
// Eg: Writing to realtime db
const companyId = event.params.companyId;
settings.getCompanyProfile(admin, companyId)
.then((profile) => {
return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(() => {
console.log('Generation Successful. Pass for email');
})
.catch((err) => {
console.log(`Error: ${err}`);
});
};
Để tạo PDF, đây là mã của tôi:
exports.generatePDF = (fonts, companyInfo, quotationData, storage) => {
const printer = new PdfPrinter(fonts);
const docDefinition = {
content: [
{
text: [
{
text: `${companyInfo.title}\n`,
style: 'companyHeader',
},
`${companyInfo.addr_line1}, ${companyInfo.addr_line2}\n`,
`${companyInfo.city} (${companyInfo.state}) - INDIA\n`,
`Email: ${companyInfo.email} • Web: ${companyInfo.website}\n`,
`Phone: ${companyInfo.phone}\n`,
`GSTIN: ${companyInfo.gst_registration_number} • PAN: AARFK6552G\n`,
],
style: 'body',
//absolutePosition: {x: 20, y: 45}
},
],
styles: {
companyHeader: {
fontSize: 18,
bold: true,
},
body: {
fontSize: 10,
},
},
pageMargins: 20,
};
return new Promise((resolve, reject) => {
// const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`);
// const filename = `${Date.now()}-quotation.pdf`;
// const file = bucket.file(filename);
// const stream = file.createWriteStream({ resumable: false });
const pdfDoc = printer.createPdfKitDocument(docDefinition);
// pdfDoc.pipe(stream);
const chunks = [];
let result = null;
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('error', (err) => {
reject(err);
});
pdfDoc.on('end',() => {
result = Buffer.concat(chunks);
resolve(result);
});
pdfDoc.end();
});
};
Điều gì có thể sai ở đây đang ngăn lời hứa và do đó báo giá mã được thực hiện như dự định?
Ngày đăng nhập căn cứ hỏa lực, tất cả tôi thấy là Function execution took 3288 ms, finished with status: 'ok'