nixn
nixn

Reputation: 1478

Firebase Functions get files from storage

I have to send a file to an API, therefor I have to use fs.readFileSync(). After uploading the picture to the storage, I am calling my function to execute the API call. But I cannot get the file from the storage. This is a section of the code, which always gets null in the result. I tried also to .getFiles() without a parameter and then I got all files but I dont want to filter them by iteration.

    exports.stripe_uploadIDs = functions.https //.region("europe-west1")
  .onCall((data, context) => {
    const authID = context.auth.uid;
    console.log("request is authentificated? :" + authID);

    if (!authID) {
      throw new functions.https.HttpsError("not authorized", "not authorized");
    }

    let accountID;
    let result_fileUpload;
    let tempFile = path.join(os.tmpdir(), "id_front.jpg");

    const options_id_front_jpeg = {
      prefix: "/user/" + authID + "/id_front.jpg"
    };

    const storageRef = admin
      .storage()
      .bucket()
      .getFiles(options_id_front)
      .then(results => {
        console.log("JPG" + JSON.stringify(results));
        // need to write this file to tempFile
        return results;
      });

    const paymentRef = storageRef.then(() => {
      return admin
        .database()
        .ref("Payment/" + authID)
        .child("accountID")
        .once("value");
    });

    const setAccountID = paymentRef.then(snap => {
      accountID = snap.val();
      return accountID;
    });

    const fileUpload = setAccountID.then(() => {
      return Stripe.fileUploads.create(
        {
          purpose: "identity_document",
          file: {
            data: tempFile,  // Documentation says I should use fs.readFileSync("filepath")
            name: "id_front.jpg",
            type: "application/octet-stream"
          }
        },
        { stripe_account: accountID }
      );
    });

    const fileResult = fileUpload.then(result => {
      result_fileUpload = result;
      console.log(JSON.stringify(result_fileUpload));
      return result_fileUpload;
    });

    return fileResult;
  });

Result is:

JPG[[]]

Upvotes: 5

Views: 5066

Answers (1)

AleC
AleC

Reputation: 522

You need to download your file from a bucket to your local function context env. After your Firebase function start executing you can call the below: More or less the below should work, just tweak to your needs. Call this within you .onCall context, you get the idea

import admin from 'firebase-admin';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';

admin.initializeApp();
const { log } = console;

async function tempFile(fileBucket: string, filePath: string) {

  const bucket = admin.storage().bucket(fileBucket);
  const fileName = 'MyFile.ext';
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const metadata = {
    contentType: 'DONT_FORGET_CONTEN_TYPE'
  };

  // Donwload the file to a local temp file
  // Do whatever you need with it
  await bucket.file(filePath).download({ destination: tempFilePath });
  log('File downloaded to', tempFilePath);

  // After you done and if you need to upload the modified file back to your
  // bucket then uploaded
  // This is optional
  await bucket.upload(tempFilePath, {
    destination: filePath,
    metadata: metadata
  });

  //free up disk space by realseasing the file.
  // Otherwise you might be charged extra for keeping memory space
  return fs.unlinkSync(tempFilePath);
}

Upvotes: 7

Related Questions