Call function from another Script Include

Kusuma2
Kilo Guru

Hi All,

 

I have Script Include1 in which  function(a) is present.

So I want to call that function(a)  in another script Include(second Script Include).

How can I achieve this?

 

gs.include("xMattersConfig");
gs.include("xMattersLogger");
gs.include('xMattersDataHelper');

var xMattersEvent = Class.create();
xMattersEvent.prototype = {
initialize: function(config, dataHelper) {
if (config && config.type == 'xMattersConfig') {
this.config = config;
} else {
this.config = new xMattersConfig();
}

this.log = new xMattersLogger(this.config.LOGLEVEL, 'xMattersEvent');

if (dataHelper && dataHelper.type == 'xMattersDataHelper') {
this.log.debug('initialize using passed in dataHelper');
this.dataHelper = dataHelper;
} else {
this.log.debug('initialize creating own dataHelper');
this.dataHelper = new xMattersDataHelper();
}

this.json = new global.JSON();

this.properties = {};
this.recipients = [];
//this.recipients2 = [];
this.conferenceBridges = [];
this.callbacks = [];
this.responses = [];
this.priority = '';
this.webserviceURL = ''; 
this.xMattersId = null;
this.response = null;
},

// Mutators to build up the correct Event values
setWebserviceURL: function( webServiceURL ) {
this.webserviceURL = webServiceURL;
},
setPriority: function( priority ) {
this.priority = priority;
},
/**
* Safely add a property to the event's property list
* @param {string} propName The key to identify the new property
* @param {string|object|null} propValue The value to assign to the new property - usually a String or GlideElement
*/
addProperty: function( propName, propValue ) {
// this.log.debug( propName + ' -- ' + typeof propValue + ' +++ ' + propValue);
// this.log.debug( 'Encoded: ' + this.json.encode( '' + propValue ) );
var strValue = '';
if( typeof propValue === 'undefined' || propValue === null) {
strValue = ''; 
} else if( typeof propValue === 'string' ) {
strValue = propValue;
} else {
if( typeof propValue.getDisplayValue === 'function' ) {
strValue = propValue.getDisplayValue();
} else {
strValue = this.json.encode( String( propValue ) ); 

}
if( strValue.length > this.config.EVENTS.MAX_FIELD_LENGTH ) {
this.log.debug( 'Truncating "' + propName + '" to ' + this.config.EVENTS.MAX_FIELD_LENGTH + ' characters' );
strValue = strValue.substr( 0, this.config.EVENTS.MAX_FIELD_LENGTH );
}
this.properties[propName] = strValue;
},
/**
* Convenience method for adding all fields from an incident to the event with the "inc__" prefix
* @param {GlideRecord[incident]} incidentRecord The incident glide record to pull values from.
*/
addAllIncidentProperties: function( incidentRecord ) {
this.log.debug( 'Adding all incident fields' );
var fields = new GlideRecord( 'sys_dictionary' );
fields.addEncodedQuery('name=task^ORname=incident');
fields.query();
var count = 0;
while( fields.next() ) {
var fieldName = fields.element;
// this.log.debug( 'Trying to add ' + fieldName );
this.addProperty( fieldName, incidentRecord.getElement( fieldName ) );
count++;
}
this.log.debug( 'Total properties added: ' + count );
},
/**
* Safely adds the target name to the list of recipients for the event
* @param {string} targetName The recipient's target name
*/ 
addRecipient: function( targetName ) {
if( typeof targetName !== 'string' || targetName.trim() === '' ) {
this.log.debug( 'Skipping invalid target: ' + targetName );
} else {
this.recipients.push( { "targetName": targetName } );
this.properties["recipients2"] = targetName;
//this.recipients2.push( { "targetName": targetName } );
}
},
/**
* Safely adds the bridge to the list of conference bridges
* @param {string|null} bridgeName The bridge's name, can be null
*/ 
addConferenceBridge: function( bridgeName ) {
var safeBridgeName = null;
if( bridgeName !== null ) {
safeBridgeName = String( bridgeName );
}
this.conferenceBridges.push( { "name": safeBridgeName } );
},
/**
* Safely sets the list of responses in the event (UUID strings)
* @param {string|array[string]} responses The response UUIDs you wish to allow users to use
* in the given event.
*/ 
setResponses: function( responses ) {
if( typeof responses === 'string' ) {
if( responses.trim() !== '' ) {
this.responses = responses.trim().split( ';' );
} else {
this.log.debug( 'Leaving responses empty' );
}
} else {
this.responses = responses;
}
},

// Convenience Getters
/**
* Gets a description of the targets/recipients
* @return {string} If recipients exist, will return a targeting string, otherwise an empty string
*/
getTargetDescription: function() {
var targStr = '';
if( this.recipients.length > 0 ) {
var targets = [];
for( var i = 0; i < this.recipients.length; i++ ) {
targets.push( this.recipients[i].targetName );
}
targStr = 'targeting (' + targets.join(', ') + ') ';
} else {
targStr = 'targeting default recipients ';
}
return targStr;
},

/**
* Gets the message to be used in the work notes log for this event
* @return {string} message that can be directly used in the work notes
*/
getEventNotes: function() {
var msg = "[xMatters] - Injected notification";
if( this.xMattersId !== null ) {
msg += " with xM event ID " + this.xMattersId + " " + this.getTargetDescription();
} else {
msg += " event FAILED " + this.getTargetDescription();
if( this.recipients.length <= 0 && this.response.status === 400 ) {
if( this.isResponseMissingRecipients( this.response ) ) {
msg += "; no default recipients configured";
}
}
}
return msg;
},

isResponseMissingRecipients: function( resp ) {
var isMissingRecipients = false;
var data = this.json.decode( resp.respData );
if( data.type === 'DATA_VALIDATION_ERROR' ) {
for( var i = 0; i < data.errorDetails.length; i++ ) {
if( data.errorDetails[i].jsonPath === 'recipients/targetName' ) {
isMissingRecipients = true;
break;
}
}
}
return isMissingRecipients;
},

/**
* Convenience method for getting the post body of the Event
* @return {object} The JSON body of the xmEvent POST request
*/
getEventBody: function() {
var body = {
"properties" : this.properties,
"priority" : this.priority
};
if( this.recipients.length > 0 ) {
//body.recipients2=
body.recipients = this.recipients;
}
if( this.conferenceBridges.length > 0 ) {
body.conferences = this.conferenceBridges;
}
if( this.callbacks.length > 0 ) {
body.callbacks = this.callbacks;
}
if( this.responses.length > 0 ) {
body.responses = this.responses;
}
this.log.debug( 'Prepared event body: ' + this.json.encode( body ) );
return body;
},

// Methods that interact with xMatters syste via the Data Helper
/**
* Sends the event -- will attempt a set number of times based on configured
* maximum attempts.
* @return {string} The id of the new event in xMatters
*/
send: function() {
var attempts = 0;
var isSuccess = false;
var message = '';
var eventId = null;
while( !isSuccess && attempts < this.config.EVENTS.MAX_ATTEMPTS ) {
attempts += 1;
try {
var resp = this.dataHelper.sendRequest( {
"method": "POST",
"endpoint": this.webserviceURL,
"path": this.webserviceURL, //added for logging
"headers": {
"Content-Type": "application/json"
},
"body": this.getEventBody()
} );
this.response = resp;
if( resp.status >= 200 && resp.status < 300 ) {
isSuccess = true;
eventId = this.json.decode( resp.body ).id;
message = "[xMatters] - created xMatters event with eventID " + eventId + " " + this.getTargetDescription();
} else {
if( this.recipients.length <= 0 && resp.status === 400 ) {
if( this.isResponseMissingRecipients( resp ) ) {
// there was no default recipient.
this.log.error( "[xMatters] - failed to create event " + this.getTargetDescription() + 
" | status: " + resp.status + " | body: " + resp.body );
message = "[xMatters] - creation of xMatters event FAILED " + this.getTargetDescription() + 
" after " + attempts + " attempts, no recipients were specified. To avoid this error, set default recipients" +
" within xmatters. please refer to logs for more details";
break;
}
}
// if didn't break, catch errors through regular error handling
this.log.error( "[xMatters] - failed to create event " + this.getTargetDescription() + 
" | status: " + resp.status + " | body: " + resp.body );

}
} catch( e ) {
this.log.error( "[xMatters] - failed to create event " + this.getTargetDescription() + 
" | error: " + String( e ) );
}
}
if( !isSuccess && message === '' ) {
message = "[xMatters] - creation of xMatters event FAILED " + this.getTargetDescription() + 
" after " + attempts + " attempts, please refer to logs for more details";
}
this.log.info( message );
this.xMattersId = eventId;
return eventId;
},
/**
* Helper method to find events in xMatters (for termination)
* @param {string} status The Status to search for
* @param {string} xMProperty The name of the property to filter by
* @param {string} value The value of the property to filter by
* @return {array} An array of events returned by the search
*/
findEvents: function( status, xMProperty, value ) {
var langSuffix = this.config.EVENTS.LANGUAGE;
var propertiesValue = encodeURIComponent( xMProperty + '#' + langSuffix + '=' + value );

var resp = this.dataHelper.sendRequest( {
"method": "GET",
"path": this.config.EVENTS.ROUTE + '?status=' + status +'&properties=' + propertiesValue,
"headers": {
"Content-Type": "application/json"
}
} );
if( resp.status >= 200 && resp.status < 300 ) {
var body = this.json.decode( resp.body );
this.log.debug( 'Successfully found ' + body.total + ' ' + status + ' events' );
return body.records;
} else {
this.log.error( 'A problem occured searching for ' + status + ' events: ' + this.json.encode( resp ) );
throw {
"response": resp,
"error": 'Searching for ' + status + ' events FAILED'
};
}
},

/**
* Terminates all active and suspended events in xMatters that have a matching
* xmProperty:value combination
* @param {string} xMProperty The name of the property in xMatters to filter by
* @param {string} value The value to filter by in xMatters
* @return {object} An object containing the records and count of terminated events
*/
terminateEvents: function( xMProperty, value ) {
this.log.debug("Entering sendTerminateEvent to delete events where " + xMProperty + " == " + value );
var activeEvents = this.findEvents( 'ACTIVE', xMProperty, value );
this.log.debug( 'Active Events: ' + this.json.encode( activeEvents ) );

var suspendedEvents = this.findEvents( 'SUSPENDED', xMProperty, value );
this.log.debug( 'Suspended Events: ' + this.json.encode( suspendedEvents ) );

var eventsForTermination = activeEvents.concat( suspendedEvents );
this.log.debug( 'All Events: ' + this.json.encode( eventsForTermination ) );

for(var i=0; i<eventsForTermination.length; i++) {
// if an event reference is found it is terminated
if (eventsForTermination[i].href !== null) {
var href = eventsForTermination[i].href;
this.log.debug( 'Terminating event at: ' + href );
this.dataHelper.sendRequest( {
"method": "PUT",
"path": href,
"headers": {
"Content-Type": "application/json"
},
"body": {
"status": "TERMINATED"
}
} );
}
}
return {
"event_count": eventsForTermination.length,
"records": eventsForTermination 
};
},

type: 'xMattersEvent'
};

4 REPLIES 4

Brad Tilton
ServiceNow Employee
ServiceNow Employee

You can call a script include from another script include pretty easily like this:

var osi = new otherScriptInclude();
osi.otherScriptIncludeFunction();

If that doesn't answer your question could you expand?

Thanks for the Quick Reply.

The Name of Script Include in which fuction is present is "xMattersCallback"

and the name of the function is     :     getUserName: function( empId ) {

As per you said earlier.

Is the below the correct way for my requirement?

var osi = new xMattersCallback();
osi.xMattersCallbackgetUserName();

 

Regards,

Ajay

Brad Tilton
ServiceNow Employee
ServiceNow Employee

I named my variables poorly, your example would be like this, assuming everything is in the global scope:

var empId = 'somestring'; //in your case you would be passing a real ID
var osi = new xMattersCallback();
var userName = osi.getUserName(empId);

Thanks.

I Used the fuction as below and it is working fine.(Highlighted)

workNotes += ' by ' + this.getUserName(this.params.recipient) + ' (' + this.params.device + ')';

Tested this worknotes is generating with employe name.

I need modifying in other part But Iam not sure where to modify it.

 

The msg is delivering with Employee Id.(Because the this.getTargetDescription function is generating Employee Id not the name.

Could you please guide me exactly Where can I modify in getTargetDescription FUNCTION TO DISPLAY the Employee Name.

I need to use the the same getUserName fuction in getTargetDescription function.

But Iam not sure wheren to place it.