Scripted REST API running slow

Meenal Gharat
Giga Guru

Hello all,

In our health scan report the below script has been identified as slow running script.

Below script is used to get variables using Get Method. Is there any chance to optimize the below code or it will be good to keep it same.

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response)
{
var utils = new GSLog("system.script.log.level", "Scripted REST Resource");
utils.setLevel(gs.getProperty("system.script.log.level"));

var responseObj = {}; //The object that should ultimately be returned.
var ritmNumbers;
var itemId;
var state;
var mail;
var opened;
itemId = request.getHeader('item_id');
if (!itemId) {
//If item_id header was not set , return an error.

return new sn_ws_err.BadRequestError("Unable to process request. Request header \'item_id\' not defined.");
}
//Declare the var that'll hold the RITM number while we iterate down below.
var ritm;
var ritmVariables;
utils.log("debug","ItemID" + itemId);
var gr = new GlideRecord('sc_req_item');
gr.addQuery('active','true');
gr.addQuery('cat_item', itemId);
gr.query();
if(!gr.next()){
//response.setStatus(417);
throw new sn_ws_err.NotFoundError("No record found");
//response.setHeader(item_id, 'Not a valid Item ID');
//return "Not a valid Item ID";
}
else{
while(gr.next()){
//utils.log("debug","Neeraj1");

if (gr.variable_pool.RecordType != 'Others' && gr.state != '3'&& gr.state != '4' && gr.state != '7')//gr.opened_at >= gs.beginningOfToday())
{

ritm = gr.number;

state = gr.state.getDisplayValue();
mail = gr.u_requested_for.email;
opened = gr.opened_at.getDisplayValue();
ritmVariables = gr.variables;
var variablesObject;
variablesObject = {};
variablesObject["state"] = state;
variablesObject["Requestor Email"] = mail;
variablesObject["Request Opened at"] = opened;
for (var v in ritmVariables) {
if (ritmVariables.hasOwnProperty(v) && ritmVariables[v]){
var variableName = v.toString();//Make sure we're all proper strings here.
variablesObject[variableName] = ritmVariables[variableName].toString();
}
}
responseObj = addObjToObj(responseObj, variablesObject, ritm);
response.setHeader('Notes', 'Returning only those variables which are populated');

}

}
return responseObj;
}
})(request, response);

function addObjToObj(parent, child, name)
{
parent[name] = child;
return parent;
}

 

 

Thanks and Regard,

Meenal

1 REPLY 1

Sajilal
Mega Sage

Please prefer not to have conditions or validations inside while loop like below. A for loop with if conditions inside a while loop would ideally cause slowness.

for (var v in ritmVariables) {
if (ritmVariables.hasOwnProperty(v) && ritmVariables[v]){
var variableName = v.toString();//Make sure we're all proper strings here.
variablesObject[variableName] = ritmVariables[variableName].toString();
}

Please Mark as ✅ Correct if this solves your issue and also mark ???? Helpful if it helps resolve your problem.

Thanks,
Saji