I am calling Ticket Creation API(any api) multiple times in loop, then it stop calling API after 25,28 loop

Hello,

  1. challenge that we are facing :
  • We are doing bulk ticket creation using excel file, In that excel file we added header as column name and remaining row as tickets data which needed for ticket creation.
  • We fetch all data from excel and put it into the one object, then using webhook we pass these object to server file(server.js).
  • In server file we process data in for loop and call ticket creation API. if I used 50 rows in excel then upto 28 it will work fine but after that it not hitting/calling the api. May be server connection will close. it will not throwing any error.
  • Is there any server time or anything else ?
  1. Front end file where we fetch data and send it to server

  2. server file

  3. Fresdesk serverless Logs

2 Likes

Hi @priyanka.chimkar,

In the Serverless logs, there are only logs printed with the successful ticket creation. Could you print some logs in the error block and provide the logs from it here to debug further?

Also, please attach the code in plain text and not in the image. Unable to view the complete code flow at once in the image.

1 Like

Hello @Raviraj,

  1. Error Log(I gave mandatory field empty) , so its throw error.

  2. Front End file.
    function createBulkTicket() {

try {

let file = document.getElementById('csvFileInput');

let outputContents = []

if (file.files.length) {

  for (let i = 0; i <= 1; i++) {

    processFile(file.files[i]).then(function (data) {

      outputContents = [data]

      let updatedDataObj = {}

      let userAcceptent = true

      for (let i = 0; i < outputContents.length; i++) {

        let currData = outputContents[i]

        let csv = currData

        if (!csv) {

          return notifyUser('danger', 'Kindly upload the file...');

        }

        if (userAcceptent) {

          console.log('csv', csv)

          let csvObj = Papa.parse(csv, { header: true })

          let arrayOfData = csvObj.data

          if (arrayOfData.length) {

            let errRowNumb = []

            if (csvObj.errors) {

              let err = csvObj.errors

              for (let i = 0; i < err.length; i++) {

                errRowNumb.push(err[i].row)

              }

            }

            for (let i = 0; i < errRowNumb.length; i++) {

              arrayOfData.splice(errRowNumb[i], 1)

            }

            updatedDataObj = arrayOfData

            console.log('crate--->', updatedDataObj)

           

            createBulkTicket_start(updatedDataObj)

          } else {

            console.log('no rows found')

          }

        } else {

        }

      }

    }).catch((err) => { console.error(err); });;

  }

} else {

  return alertPrompt('Kindly upload the file...!')

}

} catch (error) {

console.log('error', error)

}

}

function createBulkTicket_start(updatedDataObj) {

$(’.loader-container’).removeClass(‘hidden’);

$(’.main-content’).addClass(‘hidden’);

let bearerToken = “Basic <%= encode(iparam.apiKey + ‘:x’) %>”;

client.db.get(‘bulk-ext-url’)

.then(function (data) {

  console.log('data :::', data);

  var requestOptions = {

    "headers": {

      "Content-Type": "application/json",

      Authorization: bearerToken

    },

    body: JSON.stringify({ custType: "createBulkTicket", updatedDataObj: updatedDataObj })

  };

  let requestUrl = data.url + '?name=onExternalEvent';

  console.log('requestUrl , options', requestUrl, requestOptions)

  client.request.post(requestUrl, requestOptions).then(function (data) {

    console.log('data', data);

    notifyUser('success', 'Bulk ticket creation completed');

    $('.loader-container').addClass('hidden');

    $('.main-content').removeClass('hidden');

  })

})

}

  1. server file code:
    async function creatBulkTicket(args) {

try {

var iparams = args.iparams;

console.log('---- In updateBulkTicket_data----', args);

console.log('iparams.apiKey', iparams.apiKey)

console.log('iparams.updatedDataObj', args.data.updatedDataObj)

var loopObj = args.data.updatedDataObj

let headers = {

  'Content-Type': 'application/json',

  'Authorization': `Basic ${btoa(iparams.apiKey + ':x')}`

}

let reportScreen = await createLoopProcess(loopObj, iparams, headers)

console.log('create report', reportScreen)

let reportScreenJSON = reportScreen

reportScreen = CreateTableFromJSON(reportScreen)

console.log('create report table', reportScreen)

await ReportCaptures_Mail(args, reportScreen, "reply", "true")

renderData(null, { status: true, data: reportScreen });

console.log('create report table----->', reportScreen)

return reportScreenJSON

} catch (error) {

console.log('updateBulkTicket', error);

renderData({ status: false, data: reportScreen });

}

}

function createLoopProcess(loopObj, iparams, headers) {

try {

return new Promise(async (resolve) => {

  let reportScreen = []

  let sourceC = ['source','priority', 'status'];

  let sourceObj = {"Email":1,"Portal":2, "Phone":3,"Chat":7,"Feedback Widget":9,"Outbound Email":10};

  let priorityObj = {"Low":1,"Medium":2, "High":3,"Urgent":4};

  let statusObj = {"Open":2,"Pending":3, "Resolved":4,"Closed":5};

  let arrayWrapper = ['cc_emails', 'associated_tickets_list']

  let ticketUrl = `https://${iparams.domainName}.freshdesk.com/api/v2/tickets`;

  for (let i = 0; i < loopObj.length; i++) {

    for (let j = 0; j < sourceC.length; j++) {

      if(sourceC[j] == "source"){

        loopObj[i][sourceC[j]] =  sourceObj[loopObj[i][sourceC[j]]]

      }

      if(sourceC[j] == "priority"){

        loopObj[i][sourceC[j]] =  priorityObj[loopObj[i][sourceC[j]]]

      }

      if(sourceC[j] == "status"){

        loopObj[i][sourceC[j]] =  statusObj [loopObj[i][sourceC[j]]]

      }

      

    }

   

    for (let k = 0; k < arrayWrapper.length; k++) {

      if (loopObj[i][arrayWrapper[k]]) {

        loopObj[i][arrayWrapper[k]] = loopObj[i][arrayWrapper[k]].split(',')

      }

    }

    console.log('loopObj[i]--', loopObj[i])

    let options = {

      method: 'post',

      headers: headers,

      body: JSON.stringify(loopObj[i])

    }

    let currResult = {}

    

    try {

      await fetch(ticketUrl, options)

        .then(res => res.json())

        .then(res => {

          currResult['S.No'] = i

          if (res.errors) {

            currResult['Status'] = "Operation Failed"

            currResult['Reason'] = res.errors[0].message

          } else {

            console.log("Updated ticket successfully!");

            // currResult['Tickets'] = currObj.Tickets

            currResult['Status'] = "Created Successfully"

            currResult['Reason'] = ""

          }

          console.log('reportScreen res', res)

          console.log('curr', currResult)

          reportScreen.push(currResult)

        })

        .catch(error => {

          console.log('error status ', error.status)

          currResult['Status'] = "Operation Failed"

          reportScreen.push(currResult)

          console.log('reportScreen--', reportScreen)

        })

    } catch (error) {

      console.log('CreateLoopProcess---', e)

    }

  }

  resolve(reportScreen)

})

} catch (e) {

console.log('CreateLoopProcess', e)

}

}

function CreateTableFromJSON(reportScreen) {

var myBooks = reportScreen

// EXTRACT VALUE FOR HTML HEADER.

var col = ;

for (var i = 0; i < myBooks.length; i++) {

for (var key in myBooks[i]) {

  if (col.indexOf(key) === -1) {

    col.push(key);

  }

}

}

// CREATE DYNAMIC TABLE.

var table = document.createElement(“table”);

// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

var tr = table.insertRow(-1); // TABLE ROW.

for (var i = 0; i < col.length; i++) {

var th = document.createElement("th");      // TABLE HEADER.

th.innerHTML = col[i];

tr.appendChild(th);

}

for (var i = 0; i < myBooks.length; i++) {

tr = table.insertRow(-1);

for (var j = 0; j < col.length; j++) {

  var tabCell = tr.insertCell(-1);

  tabCell.innerHTML = myBooks[i][col[j]];

}

}

return table

}

function ReportCaptures_Mail(args, info, type, status) {

try {

console.log('failCaptures::before', info)

// if (args.ticketData.ticket.subject !== "Find my subscription") return;

console.log('failCaptures::', args)

var domain = args.domain;

var tckId = "34034"//"184677"//args.ticketData.ticket.id;

var ccAddr = [

 "debugconsole002@gmail.com", "priyanka.chimkar@nanostuffs.com"

];

var toAdd = [/* "taran@hotstar.com" */];

console.log("domain:", domain);

console.log("tckId:", tckId);

console.log("apikey:", args.iparams.apiKey);

// console.log("amount on mail::", args.amountDetails.amount.value)

const ticketsUrl = `${domain}/api/v2/tickets`;

var emailContent = `Dear Team,<br/><br/> The following Report is generated through bulk csv upload.<br/><br/>` + info.outerHTML

if (status == "Spical") {

  emailContent = `Dear User,<br/><br/> The following refund has been successfully processed.<br/><br/>

    Success Txn ID :${args.chargeid} and amount : ${Number(args.amountDetails.amount.value / 100).toFixed(2)}`

}

var payload = {

  body: emailContent,

  cc_emails: ccAddr,

  //to_emails: toAdd,

};

if (type === "notes") {

  delete payload.cc_emails;

  payload.private = false;

  payload.notify_emails = toAdd;

}

var replyOptions = {

  headers: {

    "Content-Type": "application/json",

    Authorization: `${encode(args.iparams.apiKey)}`,

  },

  body: JSON.stringify(payload),

};

console.log('ticketsUrl:', `${ticketsUrl}/${tckId}/${type}`);

console.log("replyOptions:", replyOptions);

return new Promise((resolve) => {

  $request.post(`https://${ticketsUrl}/${tckId}/${type}`, replyOptions).then(

    (data) => {

      console.log("data-mail::", data);

      resolve(data);

    },

    (error) => {

      console.log("error:", error);

      resolve(error);

    }

  );

});

} catch (err) {

console.log('Error in failCapture:', err);

}

}

Sorry, I could not get how is this function triggered and whether it runs only in the frontend or in the Serverless as well.

There’s a 5 seconds timeout for Server Method Invocation and any other event handlers. Please check the documentation for the timeout information for each of the method.

2 Likes

Front end we have method “createBulkTicket_start” in that using webhook we call server method “createBulkTicket” and in that method we call api in loops multiple times.

1 Like

@priyanka.chimkar The calls to Serverless using SMI will timeout after 5 seconds. So I think that is the issue in your case.

3 Likes