5

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[[]]
3
  • 1
    It's not clear to me what you're trying to do here. It doesn't help that your code snippet isn't a complete Cloud Function definition - I can't tell what kind of trigger it is. Could you edit your question to be more clear? Commented Sep 1, 2018 at 20:08
  • I have updated the code Commented Sep 1, 2018 at 20:15
  • Sounds like you want to use download() on a File object that you create. cloud.google.com/nodejs/docs/reference/storage/1.7.x/… Commented Sep 1, 2018 at 20:31

1 Answer 1

7

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.