1

I am experimenting with Firebase cloud functions and PDFs. I would like to send a PDF via email and save the Access token in Firebase database. My cloudfunctions looks like current code:

exports.invoice = functions
  .https
  .onRequest( (req,  res) => {
    const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag-2.pdf');
    const doc = new pdfkit({ margin: 50 });
    const stream = doc.pipe(myPdfFile.createWriteStream());

    doc.fontSize(25).text('Test 4 PDF!', 100, 100);
    doc.end();

 
        
    return res.send('Arbeitsvertrag-2.pdf');

  });

Via this code a PDF is stored in firebase storage. enter image description here

Only no access token is created. Is there any way to do this by default?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Joppe Meijers
  • 301
  • 4
  • 24
  • See this specific answer: https://stackoverflow.com/a/43764656/209103 – Frank van Puffelen Mar 28 '21 at 23:26
  • @FrankvanPuffelen thanks for the quick response! But uploading files succeeds, but no acces token is created if I upload it via node js cloud functions, you have an explanation for this? – Joppe Meijers Mar 28 '21 at 23:32
  • If you look at the answer I linked in my comment (and Reza's answer below), it shows how to add metadata to the file in Storage to give it an access token. – Frank van Puffelen Mar 29 '21 at 00:29

1 Answers1

3

you can do this as well to get download url and include the url in the email.

If your file is already exists in firebase storage and you want to get the public url

const bucket = admin.storage().bucket();

const fileInStorage = bucket.file(uploadPath);
const [fileExists] = await fileInStorage.exists();
if (fileExists) {
        const [metadata, response] = await fileInStorage.getMetadata();

        return metadata.mediaLink;
}

If you want to upload the file and same time get download url

    const bucket = admin.storage().bucket();

    // create a temp file to upload to storage
    const tempLocalFile = path.join(os.tmpdir(), fileName);

    const wstream = fs.createWriteStream(tempLocalFile);
    wstream.write(buffer);
    wstream.end();

    // upload file to storage and make it public + creating download token
    const [file, meta] = await bucket.upload(tempLocalFile, {
        destination: uploadPath,
        resumable: false,
        public: true,
        metadata: {
            contentType: 'image/png',
            metadata: {
                firebaseStorageDownloadTokens: uuidV4(),
            },
        },
    });

    //delete temp file
    fs.unlinkSync(tempLocalFile); 

    return  meta.mediaLink;

Reza
  • 18,865
  • 13
  • 88
  • 163