John Caruso
Kilo Guru

In Part 2 we created a simple mapGR function that factors out some of the common field mapping logic often seen in record-level processing logic.

For this short article, we'll add a second argument to helper function that works like a SQL SELECT clause defining what fields should be returned and how their values should be mapped.

function mapGR(gr, select) {
    'use strict';

    function mapValue(field, map) {
        if (typeof map === 'function') return map(gr);
        var name = map.displayValue || map.value || field;
        var el = gr.getElement(name);
        if (el === null) return null;
        if ('displayValue' in map) return el.getDisplayValue();
        return el.toString();
    }

    function mapField(obj, field) {
        var map = typeof select === 'object' ? select[field] : { value: field };
        obj[field] = mapValue(field, map);
        return obj;
    }

    var fields = typeof select === 'object' ? Object.keys(select) : Object.keys(gr).sort();
    return fields.reduce(mapField, {});
}

Here's the prior code example from Part 2 refactored to take advantage of the new functionality:

function ex_3() {
    var gr = new GlideRecord('sys_cluster_state');
    gr.get('status', 'online');

    return mapGR(gr, {
        sys_id: {},
        system_id: {},
        status: {},
        status_display: { displayValue: 'status' },
        last_checkin: { value: 'most_recent_message' },
        last_checkin_friendly: function(gr) {
            var lastDate = new GlideDateTime(gr.most_recent_message).getNumericValue();
            return Math.floor((Date.now() - lastDate) / 1000) + ' seconds';
        }
    });
}

Stay tuned, there's much more to come!

Version history
Last update:
‎10-08-2019 06:06 PM
Updated by: