Last active
March 22, 2022 15:24
-
-
Save ChecksumFailed/478c89a5401aa9fe5fcb9a77c7c4ac5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cf_ClientCommonsAjax = Class.create(); | |
cf_ClientCommonsAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, { | |
/** | |
* Dot walk object until last property reached | |
* @param {Object} obj obj | |
* @param {Array} props array of object properties | |
* @returns the last object value | |
*/ | |
_dotWalkObj: function(obj, props) { | |
props = Array.isArray(props) ? props : props.split('.'); | |
var item = props.shift(); | |
var arrLen = props.length; | |
obj = obj[item]; | |
return arrLen == 0 ? obj : this._dotWalkObj(obj, props); | |
}, | |
/** | |
* | |
* @param {GlideRecord} rec - GlideRecord Object to retrieve field value from | |
* @param {Array} fields - Array of fields to loop through and retrieve | |
* @returns {object} | |
*/ | |
_createObject: function(rec, fields) { | |
if (!Array.isArray(fields)) { | |
fields = fields.toString().split(','); | |
} | |
var tmpObj = {}; | |
for (var i = 0; i < fields.length; i++) { | |
tmpObj[fields[i]] = this._dotWalkObj(rec, fields[i]).toString(); | |
} | |
return tmpObj; | |
}, | |
/** | |
* Lookup record(s) from table. If fields param is not set, sys_id is the default | |
* Example: | |
* var params = { | |
"table":"sys_user", | |
"query":"active=true", | |
"fields" : "name","email,location.name", | |
"limit":10 | |
}; | |
var ga = new GlideAjax('cf_ClientCommonsAjax'); | |
ga.addParam('sysparm_name','lookupRecords'); | |
ga.addParam('sysparm_data',JSON.stringify(params)); | |
ga.getXMLAnswer(function (answer) { | |
console.log(answer); | |
}); | |
* @param {string} params - JSON name value pairs. | |
{ | |
table - [MANDATORY] table to query | |
query - [MANDATORY] query to use | |
fields -[Optional] list or array of fields to return from record | |
limit - [Optional] number of rows to return | |
} | |
* @returns {string} | |
*/ | |
lookupRecords: function() { | |
try { | |
var returnArr = []; | |
var params = JSON.parse(this.getParameter('sysparm_data')); | |
if (JSUtil.nil(params.table) || JSUtil.nil(params.query)) { | |
throw new Error("Table and query variables required"); | |
} | |
var grRec = new GlideRecord(params.table); | |
grRec.addEncodedQuery(params.query); | |
if (params.limit) { | |
grRec.setLimit(params.limit); | |
} | |
grRec.query(); | |
while (grRec.next()) { | |
returnArr.push(this._createObject(grRec, params.fields || ['sys_id'])); | |
} | |
return JSON.stringify(returnArr); | |
} catch (ex) { | |
return ex.message || ex; | |
} | |
}, | |
type: 'cf_ClientCommonsAjax' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment