Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add async to google cloud function?

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 
                })
            }
        });
    })
})
like image 338
Shubham Pratik Avatar asked Jan 27 '23 17:01

Shubham Pratik


2 Answers

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(/**/)...
  }
);
like image 95
Jojo Narte Avatar answered Jan 29 '23 06:01

Jojo Narte


Since async/await is an ES2017 feature, you need to add that to your .eslintrc.js:

module.exports = {
    // ...
    "parserOptions": {
        "ecmaVersion": 2017
    },
    // ...
}
like image 33
Tim Bouma Avatar answered Jan 29 '23 07:01

Tim Bouma