SlightlyLoony
Tera Contributor

In today's post, I'm going to show you a JavaScript class (in a script include, of course) whose main purpose is to serve as something we'll extend in following posts. There are (at least!) four different ways that you can extend a JavaScript class on the Service-now platform. Each of the different ways is useful in different situations. If you understand how the four techniques work, you'll understand a great deal about JavaScript classes work.

So what are these ways? We'll take 'em one at a time, starting tomorrow. For today, we'll just make a class that we can extend later. The class I've chosen is a utility class designed to make it easier and simpler for scripts to work with GlideRecords. I'm going to call it "GRUtil", and here's what it will do for starters:

The first method I'm implementing is named getTables(), and it returns an array with the tables that comprise the given table. For instance, if we execute the following code:


var gru = new GRUtil();
gs.log(gru.getTables('cmdb_ci_win_server'));

We'll get these results:

cmdb_ci_win_server,cmdb_ci_server,cmdb_ci_computer,cmdb_ci_hardware,cmdb_ci

And those are, in fact, all the tables that are part of the cmdb_ci_win_server table.

The code for this starting version of the GRUtil object is below. The code in the getTables() method does two things that may be unfamiliar to you. First, it calls into the Java object named DBObjectManager to return the list of component tables. This is one of the Java objects that we expose (make available) to JavaScript, and you can see it used in various places in the scripts that we supply. Here we're basically wrapping it in a friendly JavaScript method to make it easier to use from script. The second thing that's likely new to you is the use of the j2js() function. This is a global function that's defined in it's own eponymously named script include. It does something very simple, but quite useful: it turns most Java values into JavaScript values. In this case, it's turning the Java ArrayList returned by DBObjectManager.getTables0() into a JavaScript array. The JavaScript array is much more convenient for your JavaScript to use.

That's it for today! Tomorrow we'll extend this thing...for the first of four times...

var GRUtil = Class.create();

GRUtil.prototype = {
initialize : function() {
},

/*
* Returns an array containing the component tables for the given table. For instance, given
* 'cmdb_ci_win_server', returns an array with 'cmdb_ci_win_server', 'cmdb_ci_server',
* 'cmdb_ci_computer', 'cmdb_ci_hardware', and 'cmdb_ci'.
*/
getTables: function(table) {
var om = Packages.com.glide.db.DBObjectManager.get();
var tables = om.getTables0(table);
return j2js(tables);
}
}