What problem do Script Includes solve?
Without Script Includes, developers copy and paste the same logic into multiple Business Rules and scheduled jobs. When the logic needs to change, every copy needs updating. Script Includes give you one place to maintain shared server-side code.
Basic Script Include structure
var NowSpectrumUtils = Class.create();
NowSpectrumUtils.prototype = {
initialize: function() {},
getActiveIncidents: function(assignedTo) {
var incidents = [];
var gr = new GlideRecord('incident');
gr.addEncodedQuery('active=true^assigned_to=' + assignedTo);
gr.query();
while (gr.next()) {
incidents.push({
number: gr.getValue('number'),
short_description: gr.getValue('short_description'),
state: gr.getValue('state')
});
}
return incidents;
},
type: 'NowSpectrumUtils'
};
Calling a Script Include from a Business Rule
(function executeRule(current, previous) {
var utils = new NowSpectrumUtils();
var incidents = utils.getActiveIncidents(current.getValue('assigned_to'));
gs.log('Active incidents: ' + incidents.length);
})(current, previous);
Static Script Includes (no instantiation needed)
If you tick the Client callable checkbox and set the script up as a static class, you can call methods without instantiating:
var StaticUtils = {
formatDate: function(glideDateTimeStr) {
return glideDateTimeStr.substring(0, 10);
}
};
Client-callable Script Includes (GlideAjax)
To call a Script Include from a Client Script, you need to:
- Check the Client callable checkbox on the Script Include record
- Extend
AbstractAjaxProcessor - Return data using
this.newItem()
var IncidentAjax = Class.create();
IncidentAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getIncidentCount: function() {
var gr = new GlideRecord('incident');
gr.addEncodedQuery('active=true');
gr.query();
return gr.getRowCount().toString();
},
type: 'IncidentAjax'
});
Common mistakes
Mistake 1: Putting database queries directly in Business Rule scripts instead of a Script Include. Fix: move all reusable query logic to a Script Include.
Mistake 2: Not returning from functions. Forgetting the return statement means the caller gets undefined silently.
Mistake 3: Calling a non-client-callable Script Include from a Client Script. This throws an error at runtime.