diff --git a/Server-Side Components/Script Includes/UpdateWatchlistFromJSON/README.md b/Server-Side Components/Script Includes/UpdateWatchlistFromJSON/README.md new file mode 100644 index 0000000000..2257a7d41e --- /dev/null +++ b/Server-Side Components/Script Includes/UpdateWatchlistFromJSON/README.md @@ -0,0 +1,13 @@ +UseCase - + +Update the watchlist of any table record with the provided JSON payload which should maintain the previous watchlist user and add new one from the payload + +Payload can be Array, String, List of String + +//Passing List of String of SysId of users +var payload = '43435efdsre4t5953439434,43434343436fdfsd343,frtgr6565hg676767gt'; +updateWatchlistFromJSON('incident','a1b2c3d4e5f678901234567890abcdef', payload); + +//Passing Array of String of SysId of users +var payload = '[43435efdsre4t5953439434,43434343436fdfsd343]'; +updateWatchlistFromJSON('incident','a1b2c3d4e5f678901234567890abcdef', payload); \ No newline at end of file diff --git a/Server-Side Components/Script Includes/UpdateWatchlistFromJSON/script.js b/Server-Side Components/Script Includes/UpdateWatchlistFromJSON/script.js new file mode 100644 index 0000000000..781113a2d6 --- /dev/null +++ b/Server-Side Components/Script Includes/UpdateWatchlistFromJSON/script.js @@ -0,0 +1,34 @@ +function updateWatchlistFromJSON(tableName, recordSysId, jsonPayload) { + // Check for valid 'watch_list' data + if (jsonPayload) { + gs.error("JSON must not be empty"); + return; + } + var data = JSON.parse(jsonPayload); + // Check if data is array else convert List of string to array + var newWatchers = Array.isArray(data) ? data : data.split(','); + + // fetch the record by table name and record sys id + var gr = new GlideRecord(tableName); + if (gr.get(recordSysId)) { + // get the existing watchlist data + var existingWatchlist = gr.watch_list ? gr.watch_list.split(',') : []; + + // Add the new watchlist sys ids into exisitng watchlist + for (var i = 0; i < newWatchers.length; i++) { + var watcher = newWatchers[i]; + existingWatchlist.push(watcher); + } + + } + // Remove the duplicate by using SET + var watcherSet = new Set(existingWatchlist); + // Update the newlist into watchlist + gr.watch_list = Array.from(watcherSet).join(','); + gr.update(); + + gs.info("Watchlist updated successfully for Table "+tableName+": " + gr.number); + } else { + gs.error("Record not found for Table "+tableName+": " + recordSysId); + } +}