Skip to content

Commit ebd1df6

Browse files
Update Watchlist of any Table based on payload (ServiceNowDevProgram#1940)
* Update Watchlist of any Table based on payload * Update Watchlist of any Table based on payload * Update Watchlist of any Table based on payload
1 parent 695d030 commit ebd1df6

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
UseCase -
2+
3+
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
4+
5+
Payload can be Array, String, List of String
6+
7+
//Passing List of String of SysId of users
8+
var payload = '43435efdsre4t5953439434,43434343436fdfsd343,frtgr6565hg676767gt';
9+
updateWatchlistFromJSON('incident','a1b2c3d4e5f678901234567890abcdef', payload);
10+
11+
//Passing Array of String of SysId of users
12+
var payload = '[43435efdsre4t5953439434,43434343436fdfsd343]';
13+
updateWatchlistFromJSON('incident','a1b2c3d4e5f678901234567890abcdef', payload);
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function updateWatchlistFromJSON(tableName, recordSysId, jsonPayload) {
2+
// Check for valid 'watch_list' data
3+
if (jsonPayload) {
4+
gs.error("JSON must not be empty");
5+
return;
6+
}
7+
var data = JSON.parse(jsonPayload);
8+
// Check if data is array else convert List of string to array
9+
var newWatchers = Array.isArray(data) ? data : data.split(',');
10+
11+
// fetch the record by table name and record sys id
12+
var gr = new GlideRecord(tableName);
13+
if (gr.get(recordSysId)) {
14+
// get the existing watchlist data
15+
var existingWatchlist = gr.watch_list ? gr.watch_list.split(',') : [];
16+
17+
// Add the new watchlist sys ids into exisitng watchlist
18+
for (var i = 0; i < newWatchers.length; i++) {
19+
var watcher = newWatchers[i];
20+
existingWatchlist.push(watcher);
21+
}
22+
23+
}
24+
// Remove the duplicate by using SET
25+
var watcherSet = new Set(existingWatchlist);
26+
// Update the newlist into watchlist
27+
gr.watch_list = Array.from(watcherSet).join(',');
28+
gr.update();
29+
30+
gs.info("Watchlist updated successfully for Table "+tableName+": " + gr.number);
31+
} else {
32+
gs.error("Record not found for Table "+tableName+": " + recordSysId);
33+
}
34+
}

0 commit comments

Comments
 (0)