SlightlyLoony
Tera Contributor
Options
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
07-26-2010
07:41 AM
Have you found yourself writing almost the same code, over and over again? I recently spoke with someone who had very similar code in several different places, always to get a related list of a CI. Each time, the same dozen or so lines of code appeared with only trivial differences between them. What would be nice is if you could instead write code like this when you needed to get a GlideRecord with the disks related to a computer (just as an example):
var gr = getComputerByName('tbr');
var disks = getRL(gr, 'cmdb_ci_disk');
But how would you do that?
Take a look at the code below, which provides the abstraction that allows the code above to work:
var getComputerByName = getGRFactory('cmdb_ci_computer', 'name');
var gr = getComputerByName('tbr');
var disks = getRL(gr, 'cmdb_ci_disk');
while (disks.next())
gs.log('Disk: ' + disks.name);
function getRL(gr, related) {
var target = gr.getTableName() + '';
var ref_field = getReferenceField(target, related);
var answer = new GlideRecord(related);
answer.addQuery(ref_field, gr.getUniqueValue());
answer.query();
return answer;
}
function getReferenceField(target, related) {
var possible_targets = Packages.com.glide.db.DBObjectManager.getTables(target);
var dgr = new GlideRecord('sys_dictionary');
dgr.addQuery('name', related);
dgr.addQuery('internal_type', 'reference');
dgr.addQuery('reference', possible_targets);
dgr.query();
return dgr.next() ? '' + dgr.element : null;
}
function getGRFactory(table, field) {
var f_table = table;
var f_field = field;
return getter;
function getter(value) {
return getGR(f_table, f_field, value);
}
}
function getGR(table, field, value) {
var gr = new GlideRecord(table);
gr.addQuery(field, value);
gr.query();
gr.next();
return gr;
}
I used closures and a factory method to build the getComputerByName() function, and a generalized getRL() function to get any directly related list, given the GlideRecord of a base table. In this case the base table was one row of cmdb_ci_computer, representing a computer named 'tbr'. The getReferenceField() function searches the dictionary to find the field in the related list that is a reference to the base table (or one of its parents). Not too much code, and now you've got a completely generalized capability to find any related list. For instance, with the same functions, this code will return a list of network adapters for a computer, and list the MAC addresses:
var gr = getComputerByName('tbr');
var nics = getRL(gr, 'cmdb_ci_network_adapter');
while (nics.next())
gs.log('NIC: ' + nics.name + ' - ' + nics.mac_address);
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.