Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Recursive GlideRecord Fetcher
## Overview
This snippet provides a reusable logic to recursively fetch child records from a parent record in ServiceNow. It is useful for traversing hierarchical relationships such as tasks, categories, CMDB CI relationships, or any table with a parent-child structure.

The logic prevents infinite loops by tracking visited records and supports nesting of children for structured output.

---

## Use Case
- Fetch all subtasks under a parent task.
- Traverse CMDB CI relationships recursively.
- Build hierarchical views of organizational units or categories.

---

## Parameters
| Parameter | Description |
|------------------|-----------------------------------------------------------------------------|
| `tableName` | Name of the table to query (e.g., `task`, `cmdb_ci`, `custom_table`) |
| `parentField` | Field that links to the parent record (e.g., `parent`, `parent_id`) |
| `parentSysId` | Sys ID of the root parent record to start traversal |

---

## Example Usage
```javascript
var fetcher = new RecursiveFetcher('task', 'parent');
var hierarchy = fetcher.fetchChildren('abc123sysid'); // Replace with actual parent sys_id
gs.info(JSON.stringify(hierarchy));
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
var RecursiveFetcher = Class.create();
RecursiveFetcher.prototype = {
initialize: function(tableName, parentField) {
this.tableName = tableName;
this.parentField = parentField;
this.visited = [];
},

fetchChildren: function(parentSysId) {
if (this.visited.indexOf(parentSysId) !== -1) {
// Avoid infinite loops
return [];
}

this.visited.push(parentSysId);
var children = [];

var gr = new GlideRecord(this.tableName);
gr.addQuery(this.parentField, parentSysId);
gr.query();

while (gr.next()) {
var child = {
sys_id: gr.getValue('sys_id'),
name: gr.getDisplayValue('name') || gr.getDisplayValue('short_description'),
children: this.fetchChildren(gr.getValue('sys_id')) // Recursive call
};
children.push(child);
}

return children;
},

type: 'RecursiveFetcher'
};

// Example usage:
//var fetcher = new RecursiveFetcher('task', 'parent');
//var hierarchy = fetcher.fetchChildren('abc123sysid'); // Replace with actual parent sys_id
//gs.info(JSON.stringify(hierarchy));
``
Loading