Home > Back-end >  Call async function via PUT API call
Call async function via PUT API call

Time:08-24

I have a function which needs to be called when I hit the PUT API. Actually what I want to achieve is, a file gets created when the API is called.. lets say via Postman and that file needs to be stored inside a GCP bucket... for some reason it is not working as I expect it to be... I also don't get any errors. Below is my code snippet:

app.put('/api/ddr/:ticket_id', (req, res) => {
    const ticket_id = req.params.ticket_id;
    const requestBody = req.body;
    if(!requestBody || !ticket_id){
        res.status(404).send({message: 'There is an error'});
    }
    var fs = require('fs');
    var writer = fs.createWriteStream(filename,{ 'flags': 'a'
    , 'encoding': null
    , 'mode': 0666
    });
    writer.write(JSON.stringify(requestBody));
    res.status(201).send('all ok');
    uploadFile().catch(console.error);
  });

  async function uploadFile() {
    await storage.bucket(bucketName).upload(filePath);
    console.log("Trying to upload file to bucket");
    console.log(`${filePath} uploaded to ${bucketName}`);
  }


 

CodePudding user response:

The issues are you send your response before the file has been uploaded, and you're not handling the asynchronous code, try something like this.

async function uploadFile() {
  // TODO pass these variables as parameters and dont use
  // global variables
  console.log('Trying to upload file to bucket')
  await storage.bucket(bucketName).upload(filePath)
  console.log(`${filePath} uploaded to ${bucketName}`)
}

app.put('/api/ddr/:ticket_id', async (req, res) => {
  const ticket_id = req.params.ticket_id
  const requestBody = req.body
  if (!requestBody || !ticket_id) {
    res.status(404).send({ message: 'There is an error' })
  }
  var fs = require('fs')
  fs.writeFileSync(filename, requestBody)
  try {
    // You need to await this so that the promise can resolve
    // This is very important when using a cloud function
    // Your prior code didnt handle this
    await uploadFile()
  } catch (error) {
    console.error(`File upload failed with the following error: ${error}`)
  }
  // When everything is complete, then we send a response to the client
  return res.status(201).send('all ok')
})
  • Related