Im having issues to return the urls that were created after uploading incoming files to firebase storage with firebase functions. The function upload one or more files.
Im handling the incoming files in a formdata object with busboy as suggested in the docs for google cloud functions.
While Im having success writing the files to firebase storage, im not retrieving the urls needed that are created within the scope of the busboy.on('finish') execution.
const admin = require("firebase-admin");
const cors = require("cors")({ origin: true });
const functions = require("firebase-functions");
const { uuid } = require("uuidv4");
const Busboy = require("busboy");
const fs = require("fs");
const os = require("os");
const path = require("path");
exports.uploadImage = functions.https.onRequest((request, response) => {
cors(request, response, async () => {
try {
const busboy = new Busboy({ headers: request.headers });
const tmpdir = os.tmpdir();
const uploads = {};
const fileWrites = [];
// Where I want to store the urls generated while uploading the files <---------------------------
const urls = [];
busboy.on("file", (fieldname, file, filename) => {
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
const promise = new Promise((resolve, reject) => {
file.on("end", () => {
writeStream.end();
});
writeStream.on("finish", resolve);
writeStream.on("error", reject);
});
fileWrites.push(promise);
});
const bucket = admin.storage().bucket("kameleon-b7631.appspot.com");
busboy.on("finish", async () => {
await Promise.all(fileWrites);
for (const file in uploads) {
const uniqueID = uuid();
const uploadImage = await bucket.upload(uploads[file], {
metadata: {
metadata: {
firebaseStorageDownloadTokens: uniqueID,
},
},
});
const filename = uploads[file].split("/").pop();
const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${
bucket.name
}/o/${encodeURIComponent(filename)}?alt=media&token=${uniqueID}`;
//This line doesnt trigger and doesnt update urls array <---------------------------
//but above promise to update the urls did trigger
urls.push(imgUrl);
fs.unlinkSync(uploads[file]);
}
});
busboy.end(request.rawBody);
//at this point the urls array still empty <---------------------------
return response.send(urls);
} catch (error) {
console.log("error: ", error);
return response.status(500).send(error);
}
});
});
While debugging with vscode, I can see the array never gets updated and I don't really understand why. Here's a video of it:
what Im doing wrong? How can I get the urls Any help would be much appreciated