Search code examples
javascriptgoogle-cloud-functionspdfkit

Ignoring exception from a finished function using PDFKit & GCF


So at the moment i;m trying to generate a PDF (using Node.js, PDFKit and GCF) from a number of data within my Firebase Database. One of those items is an image URL but PDF kit requires this in a base64 format. At the moment the PDF is being created but i'm getting around 6 calls of "Ignoring exception from a finished function".

I think this is to do with the base64 function but i can't seem to nail down where the issue is... the function is returning its results after the onCreate is triggered but i thought "await" is meant to stop this? Any help / thoughts?

 exports.onAppComplete = functions.database.ref("users/{appId}").onCreate((snapshot, context) =>{
            var appId = context.params.appId;
            var appDb = admin.database().ref(`Applications/${appId}`);
            return Promise.all([appDb.once('value'),appId]).then(([applicationDb, appId])=>{

                var application = {
                    appId:appId,
                    dogId:applicationDb.child("dogId").val(),
                    userId: applicationDb.child("appWith").val(),

                  };


                const Logo =  admin.database().ref(`users/logouri`);
                return Promise.all([Logo.once('value')]).then(([Logo])=>{
                    const PDFDocument = require('pdfkit');
                    let doc = new PDFDocument({ margin: 72 });
                       doc.size = [595.28, 841.89];
                       doc
                       .image('./images/logo.png', 50, 45, { width: 100 })
                         .fillColor("#444444")
                        .moveDown(1);
                        var logoUri = Logo.val();
                        console.log("pictureURL",logoUri);
                         toBase64(logoUri,50,50,doc);


                    const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag.pdf');
                    const stream = doc.pipe(myPdfFile.createWriteStream());
                    doc.end();
                    return console.log('Successfully made App PDF:', "OK");

                })
                 });
                });
          function toBase64(url, x, y, pdfdoc) {
                        return new Promise(async (resolve, reject)=>{
                            var https = require('https');
                            var req = await https.get(url, (res) => {
                                res.setEncoding('base64');
                                let body = "data:" + res.headers["content-type"] + ";base64,";
                                console.log("BODY", body)
                                res.on('data', (d) => {
                                    body += d;
                                });
                                res.on('end', () => {
                                    console.log("END", body)
                                    pdfdoc.image(body, x, y);
                                    resolve(res);
                                });
                            });
                            req.on('error', err => {
                                console.error('error!');
                                reject(err);
                            });

                        });

                    }

I'm using Node.js 8 and there is a seperate logo that is loaded locally.


Solution

  • after some prompting by doug...here's the code that answers this, it turns out that a Promise.all is key:

    exports.onAppComplete = functions.database.ref("users/{appId}").onCreate((snapshot, context) =>{
                var appId = context.params.appId;
                var appDb = admin.database().ref(`Applications/${appId}`);
                return Promise.all([appDb.once('value'),appId]).then(([applicationDb, appId])=>{
    
                    var application = {
                        appId:appId,
                        dogId:applicationDb.child("dogId").val(),
                        userId: applicationDb.child("appWith").val(),
    
                      };
    
    
                    const Logo =  admin.database().ref(`users/logouri`);
                    return Promise.all([Logo.once('value')]).then(([Logo])=>{
                        const PDFDocument = require('pdfkit');
                        let doc = new PDFDocument({ margin: 72 });
                           doc.size = [595.28, 841.89];
                           doc
                           .image('./images/logo.png', 50, 45, { width: 100 })
                             .fillColor("#444444")
                            .moveDown(1);
                            var logoUri = Logo.val();
                            console.log("pictureURL",logoUri);
                             return Promise.all([toBase64(logoUri),doc,application]).then(([logoURIBase64, doc, application])=>{
    
                doc.rect(0,0,590,70,40).fillAndStroke("#339999");
                doc.image(logoURIBase64,50,50,{width:100});
            const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag.pdf');
            const stream = doc.pipe(myPdfFile.createWriteStream());
            doc.end();
            return console.log('Successfully made App PDF:', "OK");
    
                });
    
    
                        const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag.pdf');
                        const stream = doc.pipe(myPdfFile.createWriteStream());
                        doc.end();
                        return console.log('Successfully made App PDF:', "OK");
    
                    })
                     });
                    });
              function toBase64(url) {
                            return new Promise(async (resolve, reject)=>{
                                var https = require('https');
                                var req = await https.get(url, (res) => {
                                    res.setEncoding('base64');
                                    let body = "data:" + res.headers["content-type"] + ";base64,";
                                    console.log("BODY", body)
                                    res.on('data', (d) => {
                                        body += d;
                                    });
                                    res.on('end', () => {
                                        console.log("END", body)
                                        pdfdoc.image(body, x, y);
                                        resolve(body);
                                    });
                                });
                                req.on('error', err => {
                                    console.error('error!');
                                    reject(err);
                                });
    
                            });
    
                        }