I want to use async
and add await
in bucket.upload
function. I am also using cors
in my function. But I am unable to add async
to it, because it gives error.
Here is my code:
exports.registerAdminUser = functions.https.onRequest(( request, response ) => {
return cors (request,response, ()=> {
const body = request.body;
const profile_pic = body.profile_pic;
const strings = profile_pic.base64.split(',');
const b64Data = strings[1];
const contenttype = profile_pic.type;
const uid = uniqid();
const uploadName = uid + profile_pic.name
const fileName = '/tmp/' + profile_pic.name;
fs.writeFileSync(fileName, b64Data, "base64", err => {
console.log(err);
return response.status(400).json({ error: err });
});
const bucketName = 'my-bucketname.io';
const options = {
destination: "/images/admin/" + uploadName,
metadata: {
metadata: {
uploadType: "media",
contentType: contenttype ,
firebaseStorageDownloadTokens: uid
}
}
};
const bucket = storage.bucket(bucketName);
bucket.upload(fileName,options, (err, file) => {
if(!err){
const imageUrl = "https://firebasestorage.googleapis.com/v0/b/" + bucket.name + "/o/" + encodeURIComponent(file.name) + "?alt=media&token=" + uid;
return response.status(200).json(imageUrl);
} else {
return response.send(400).json({
message : "Unable to upload the picture",
error : err.response.data
})
}
});
})
})
In your package.json
use NodeJS
engine 8.
By default GCF uses version 6. To be able to use async/await
you must change or add below inside package.json
"engines": {
"node": "8"
},
Add the async like below
exports.registerAdminUser = functions.https.onRequest(
async ( request, response ) => {
/**/
await someFunction(/**/)...
}
);
Since async/await is an ES2017 feature, you need to add that to your .eslintrc.js:
module.exports = {
// ...
"parserOptions": {
"ecmaVersion": 2017
},
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With