Reputation: 15
Whenever a user has to publish an image in the storage I don't do it directly with the firebase storage functions but using an onCall cloud function by passing it a base64 image, modifying it (5 times), and posting it in the storage.
The function is as follows:
exports.uploadImage = functions.https.onCall(async (data, context) => {
var bucket = admin.storage().bucket();
// Convert the base64 string back to an image
var base64EncodedImageString = data.image,
mimeType = 'image/jpeg',
fileName = 'testName',
imageBuffer = Buffer.from(base64EncodedImageString, 'base64');
if (!fs.existsSync(os.tmpdir()+"/myfolder")){
fs.mkdirSync(os.tmpdir()+"/myfolder");
}
const tempFilePath = path.join(os.tmpdir(),"myfolder", fileName+".jpg");
fs.writeFileSync(tempFilePath,base64EncodedImageString,'base64',function(err){
functions.logger.log("file scritto in"+tempFilePath);
})
await bucket.upload(tempFilePath, {
destination: 'test/'+fileName,
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
const tempFilePath_25 = path.join(os.tmpdir(),"myfolder", fileName+"_25.jpg");
spawnSync('convert', [tempFilePath, '-scale', '10%','-scale','1000%>', tempFilePath_25]);
await bucket.upload(tempFilePath_25, {
destination: 'test/'+fileName+"_25.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_25);
const tempFilePath_50 = path.join(os.tmpdir(),"myfolder", fileName+"_50.jpg");
spawnSync('convert', [tempFilePath, '-scale', '5%','-scale','2000%>', tempFilePath_50]);
await bucket.upload(tempFilePath_50, {
destination: 'test/'+fileName+"_50.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_50);
const tempFilePath_75 = path.join(os.tmpdir(),"myfolder", fileName+"_75.jpg");
spawnSync('convert', [tempFilePath, '-scale', '3%','-scale','3333%>', tempFilePath_75]);
await bucket.upload(tempFilePath_75, {
destination: 'test/'+fileName+"_75.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_75);
const tempFilePath_100 = path.join(os.tmpdir(),"myfolder", fileName+"_100.jpg");
spawnSync('convert', [tempFilePath, '-scale', '1%','-scale','10000%>', tempFilePath_100]);
await bucket.upload(tempFilePath_100, {
destination: 'test/'+fileName+"_100.jpg",
metadata: { contentType: mimeType,
metadata: {
firebaseStorageDownloadTokens: uuid()
}
},
});
fs.unlinkSync(tempFilePath_100);
});
I tried to do a simulation with a for loop every 2 seconds and I get the deadline error for 60% of the requests. When I publish the app there will be many users (hopefully) who can potentially call the same function simultaneously to post a photo. How can I solve this problem? Thanks in advance.
Upvotes: 0
Views: 80