Skip to content

Instantly share code, notes, and snippets.

@manvillej
Last active October 22, 2024 06:53
Show Gist options
  • Save manvillej/b94cd37c5c46899b118932b207faff86 to your computer and use it in GitHub Desktop.
Save manvillej/b94cd37c5c46899b118932b207faff86 to your computer and use it in GitHub Desktop.
/**
* Does the work on each loop.
* @param {Number} [limit=10] - The number of records to process per loop.
* @param {Number} [currentNumber=0] - The number of records that have been processed so far, by all previous loops.
*/
function eventWrapper(limit, currentNumber) {
var EVENT_NAME = 'EVENT.NAME.HERE'; //todo: Update this to the name of the event you've created.
var TABLE_NAME = 'TABLE_NAME_HERE'; //todo: Update this to the name of the table containing the records you're processing
var QUERY = 'some_query=here'; //todo: Put your query here
var initial_count;
var count = new GlideAggregate(TABLE_NAME);
count.addAggregate('COUNT');
count.AddEncodedQuery(QUERY);
count.query();
if (count.next()) {
initial_count = count.getAggregate('COUNT');
} else {
gs.error(EVENT_NAME + ": event queued with no records to process. Check your table & query in the script action");
return;
}
var gr = new GlideRecord(TABLE_NAME);
//Set default values
limit = Number(limit) > 0 ? Number(limit) : 10; //Default: 10
currentNumber = currentNumber > 0 ? currentNumber : 0; //Default: 0
gr.setLimit(limit);
gr.addQuery(QUERY);
gr.query();
while (gr.next()) {
/*
* Do something to a batch of records here, based on the limit parameter
*/
currentNumber++;
}
var new_count = 0;
count = new GlideAggregate(TABLE_NAME);
count.addAggregate('COUNT');
count.AddEncodedQuery(QUERY);
count.query();
if (count.next()) {
new_count = count.getAggregate('COUNT');
if (new_count == 0) {
gs.log('EDR: [Script name here] completed with ' + currentNumber +
' total records processed.');
return; //No more records to process. Halt function and loop.
}
}
if (new_count > (initial_count - limit)) {
gs.error(EVENT_NAME + ": script action processed less records than expected. Infinite loop is likely. Halting the loop.");
return; // risk of infinite loop. Halt function and loop.
}
//Log a progress update
gs.log(EVENT_NAME + ': event wrapper processed ' + currentNumber +
' records so far. Triggering the next loop.');
//Trigger the event again
gs.eventQueue(EVENT_NAME, gr, limit, currentNumber);
}
eventWrapper(event.parm1, event.parm2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment