Last active
May 2, 2022 19:24
-
-
Save jmbauguess/cbc5ad1fedea6d94e13c to your computer and use it in GitHub Desktop.
Converts a GlideRecord object into JSON, or converts JSON into a GlideRecord. See http://sensibleservicenow.com/?p=49
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
/** | |
* @description Converts between JSON Objects and GlideRecords | |
* @namespace | |
* @type {Class} | |
*/ | |
var JSONtoGlide = Class.create(); | |
JSONtoGlide.prototype = { | |
/** | |
* @description Converts an object into a new GlideRecord | |
* @param {Object} json A json object | |
* @return {GlideRecord} A GlideRecord object | |
* @example | |
* var incident = { "_collection_type" : "incident", "short_description" : "Example"}; | |
* var incidentRecord = new JSONtoGlide().marshall(incident); | |
*/ | |
marshall: function(json) { | |
if (!this.validateCollectionExists(json._collection_type)) { | |
gs.log("INVALID COLLECTION : " + json._collection_type, "JSONtoGlide"); | |
return ''; | |
} | |
var glideRecord = new GlideRecord(json._collection_type), | |
item; | |
if (!json.hasOwnProperty('sys_id')) { | |
glideRecord.initialize(); | |
} else { | |
glideRecord.get(json.sys_id); | |
} | |
for (item in json) { | |
if (json.hasOwnProperty(item)) { | |
glideRecord.setValue(item, json[item]); | |
} | |
} | |
if (!json.hasOwnProperty('sys_id')) { | |
glideRecord.insert(); | |
} else { | |
glideRecord.update(); | |
} | |
return glideRecord; | |
}, | |
/** | |
* @description Converts a GlideRecord into an object | |
* @param {GlideRecord} record A GlideRecord | |
* @return {Object} A json object | |
* @example | |
* var incident = new GlideRecord('incident'), | |
* object; | |
* if (incident.get('sys_id')) { | |
* object = new JSONtoGlide().unmarshall(incident); | |
* } | |
*/ | |
unmarshall: function(record) { | |
var fields = new GlideRecordUtil().getFields(record), | |
resultObject = {}, | |
field; | |
for (field in fields) { | |
resultObject[fields[field]] = record.getValue(fields[field]); | |
} | |
return resultObject; | |
}, | |
/** | |
* @description Ensures a table exists before trying to create a GlideRecord | |
* @param {String} name The name of the table | |
* @return {boolean} True if the table exists, false otherwise | |
* @example | |
* new JSONtoGlide().validateCollectionExists('incident'); //true | |
* new JSONtoGlide().validateCollectionExists('fake_table'); //false | |
*/ | |
validateCollectionExists: function(name) { | |
var table = new GlideRecord('sys_db_object'); | |
if (table.get('name', name)) { | |
return true; | |
} | |
return false; | |
}, | |
type: 'JSONtoGlide' | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment