/** * @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' };