Skip to content

Commit d66be09

Browse files
earlduqueclaude
andauthored
Add new GlideQuery Conditional Field Selection snippet and update gitignore (ServiceNowDevProgram#1637)
- Added new GlideQuery code snippet demonstrating conditional field selection patterns - Includes 5 comprehensive examples: role-based selection, performance optimization, dynamic arrays, chained conditions, and security-conscious selection - Updated .gitignore to exclude Claude Code settings (.claude/ and settings.local.json) Co-authored-by: Claude Code <[email protected]>
1 parent f491830 commit d66be09

File tree

3 files changed

+234
-1
lines changed

3 files changed

+234
-1
lines changed

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
1-
.DS_Store
1+
.DS_Store
2+
3+
# Claude Code settings
4+
.claude/
5+
settings.local.json
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Conditional Field Selection with GlideQuery
2+
3+
This snippet demonstrates how to dynamically select different sets of fields based on conditions using GlideQuery. This pattern is useful when you need to optimize queries by selecting only the fields you actually need based on runtime conditions, or when building flexible APIs that return different data sets based on user permissions or preferences.
4+
5+
## Use Cases
6+
7+
- **Permission-based field selection**: Select different fields based on user roles or permissions
8+
- **Performance optimization**: Only fetch expensive fields when needed
9+
- **API flexibility**: Return different data sets based on request parameters
10+
- **Conditional aggregations**: Include summary fields only when specific conditions are met
11+
12+
## Key Benefits
13+
14+
- **Reduced data transfer**: Only fetch the fields you need
15+
- **Performance optimization**: Avoid expensive field calculations when unnecessary
16+
- **Security**: Dynamically exclude sensitive fields based on permissions
17+
- **Maintainable code**: Centralized logic for field selection patterns
18+
19+
## Examples Included
20+
21+
1. **Role-based field selection**: Different fields for different user roles
22+
2. **Performance-optimized queries**: Conditional inclusion of expensive fields
23+
3. **Dynamic field arrays**: Building field lists programmatically
24+
4. **Chained conditional selection**: Multiple condition-based selections
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
// Conditional Field Selection with GlideQuery
2+
// Demonstrates dynamically selecting different fields based on runtime conditions
3+
4+
/**
5+
* Example 1: Role-based Field Selection
6+
* Select different incident fields based on user's role
7+
*/
8+
function getIncidentsByRole(userRole, assignedTo) {
9+
// Define base fields that everyone can see
10+
let baseFields = ['number', 'short_description', 'state', 'priority', 'sys_created_on'];
11+
12+
// Define additional fields based on role
13+
let additionalFields = [];
14+
15+
if (userRole === 'admin' || userRole === 'security_admin') {
16+
additionalFields = ['caller_id', 'assigned_to', 'assignment_group', 'work_notes', 'comments'];
17+
} else if (userRole === 'itil') {
18+
additionalFields = ['caller_id', 'assigned_to', 'assignment_group'];
19+
} else if (userRole === 'agent') {
20+
additionalFields = ['assigned_to', 'assignment_group'];
21+
}
22+
23+
// Combine base and additional fields
24+
let fieldsToSelect = baseFields.concat(additionalFields);
25+
26+
return new GlideQuery('incident')
27+
.where('assigned_to', assignedTo)
28+
.where('state', '!=', 7) // Not closed
29+
.select(fieldsToSelect)
30+
.orderByDesc('sys_created_on')
31+
.toArray(50);
32+
}
33+
34+
/**
35+
* Example 2: Performance-optimized Field Selection
36+
* Only include expensive fields when specifically requested
37+
*/
38+
function getTasksWithOptionalFields(options) {
39+
options = options || {};
40+
41+
// Always include these lightweight fields
42+
let fields = ['sys_id', 'number', 'short_description', 'state'];
43+
44+
// Conditionally add more expensive fields
45+
if (options.includeUserDetails) {
46+
fields.push('caller_id.name', 'caller_id.email', 'assigned_to.name');
47+
}
48+
49+
if (options.includeTimeTracking) {
50+
fields.push('work_start', 'work_end', 'business_duration');
51+
}
52+
53+
if (options.includeApprovalInfo) {
54+
fields.push('approval', 'approval_history');
55+
}
56+
57+
if (options.includeRelatedRecords) {
58+
fields.push('parent.number', 'caused_by.number');
59+
}
60+
61+
let query = new GlideQuery('task')
62+
.where('active', true)
63+
.select(fields);
64+
65+
if (options.assignmentGroup) {
66+
query.where('assignment_group', options.assignmentGroup);
67+
}
68+
69+
return query.toArray(100);
70+
}
71+
72+
/**
73+
* Example 3: Dynamic Field Array Building
74+
* Build field selection based on table structure and permissions
75+
*/
76+
function getDynamicFieldSelection(tableName, userPermissions, includeMetadata) {
77+
let fields = [];
78+
79+
// Always include sys_id
80+
fields.push('sys_id');
81+
82+
// Add fields based on table type
83+
if (tableName === 'incident' || tableName === 'sc_request') {
84+
fields.push('number', 'short_description', 'state', 'priority');
85+
86+
if (userPermissions.canViewCaller) {
87+
fields.push('caller_id');
88+
}
89+
90+
if (userPermissions.canViewAssignment) {
91+
fields.push('assigned_to', 'assignment_group');
92+
}
93+
} else if (tableName === 'cmdb_ci') {
94+
fields.push('name', 'operational_status', 'install_status');
95+
96+
if (userPermissions.canViewConfiguration) {
97+
fields.push('ip_address', 'fqdn', 'serial_number');
98+
}
99+
}
100+
101+
// Add metadata fields if requested
102+
if (includeMetadata) {
103+
fields.push('sys_created_on', 'sys_created_by', 'sys_updated_on', 'sys_updated_by');
104+
}
105+
106+
return new GlideQuery(tableName)
107+
.select(fields)
108+
.limit(100)
109+
.toArray();
110+
}
111+
112+
/**
113+
* Example 4: Chained Conditional Selection with Method Chaining
114+
* Demonstrate building complex queries with multiple conditions
115+
*/
116+
function getConditionalIncidentData(filters) {
117+
let query = new GlideQuery('incident');
118+
119+
// Build base field list
120+
let fields = ['sys_id', 'number', 'short_description', 'state'];
121+
122+
// Apply filters and modify field selection accordingly
123+
if (filters.priority && filters.priority.length > 0) {
124+
query.where('priority', 'IN', filters.priority);
125+
fields.push('priority'); // Include priority field when filtering by it
126+
}
127+
128+
if (filters.assignmentGroup) {
129+
query.where('assignment_group', filters.assignmentGroup);
130+
fields.push('assignment_group', 'assigned_to'); // Include assignment fields
131+
}
132+
133+
if (filters.dateRange) {
134+
query.where('sys_created_on', '>=', filters.dateRange.start)
135+
.where('sys_created_on', '<=', filters.dateRange.end);
136+
fields.push('sys_created_on'); // Include date when filtering by it
137+
}
138+
139+
if (filters.includeComments) {
140+
fields.push('comments', 'work_notes');
141+
}
142+
143+
if (filters.includeResolution) {
144+
fields.push('close_code', 'close_notes', 'resolved_by');
145+
}
146+
147+
return query.select(fields)
148+
.orderByDesc('sys_created_on')
149+
.toArray(filters.limit || 50);
150+
}
151+
152+
/**
153+
* Example 5: Security-conscious Field Selection
154+
* Exclude sensitive fields based on user context
155+
*/
156+
function getSecureUserData(requestingUser, targetUserId) {
157+
let baseFields = ['sys_id', 'name', 'user_name', 'active'];
158+
159+
// Check if requesting user can see additional details
160+
if (gs.hasRole('user_admin') || requestingUser === targetUserId) {
161+
// Full access - include all standard fields
162+
return new GlideQuery('sys_user')
163+
.where('sys_id', targetUserId)
164+
.select(['sys_id', 'name', 'user_name', 'email', 'phone', 'department', 'title', 'manager', 'active'])
165+
.toArray(1);
166+
} else if (gs.hasRole('hr_admin')) {
167+
// HR access - include HR-relevant fields but not IT details
168+
return new GlideQuery('sys_user')
169+
.where('sys_id', targetUserId)
170+
.select(['sys_id', 'name', 'user_name', 'department', 'title', 'manager', 'active'])
171+
.toArray(1);
172+
} else {
173+
// Limited access - only public information
174+
return new GlideQuery('sys_user')
175+
.where('sys_id', targetUserId)
176+
.select(baseFields)
177+
.toArray(1);
178+
}
179+
}
180+
181+
// Usage Examples:
182+
183+
// Role-based selection
184+
var adminIncidents = getIncidentsByRole('admin', gs.getUserID());
185+
186+
// Performance-optimized query
187+
var tasksWithDetails = getTasksWithOptionalFields({
188+
includeUserDetails: true,
189+
includeTimeTracking: false,
190+
assignmentGroup: 'hardware'
191+
});
192+
193+
// Dynamic field building
194+
var dynamicData = getDynamicFieldSelection('incident', {
195+
canViewCaller: true,
196+
canViewAssignment: false
197+
}, true);
198+
199+
// Complex conditional query
200+
var filteredIncidents = getConditionalIncidentData({
201+
priority: [1, 2],
202+
assignmentGroup: 'network',
203+
includeComments: true,
204+
limit: 25
205+
});

0 commit comments

Comments
 (0)