Helper util script file

At times, the payload mapping script can become large and complex. So rather than writing the entire logic in one file, you can maintain certain code as utility functions in the separate file. For example: the extraction of input details in the encode function can be written as a utility function.

var utils = Java.type('com.nokia.transformation.script.model.TransformUtil');

function getImpactRequestAsJson(impactRequest) {
    var request = {};
    request.type = utils.getRequestType(impactRequest);
    request.url = impactRequest.getResource();
    if (!request.type || !request.url) {
        throw new Error(`request type and resource URL are required in the input`);
    }
 
    // extract the last part of the URL as the resource name
    var resourceItems = request.url.split("/");
    request.resource = resourceItems[resourceItems.length - 1];
 
    // get the request data if available
    if (impactRequest.getValue) {
        request.resourceValue = impactRequest.getValue();
    }
    return request;
}

This function getImpactRequestAsJson in the utils file can be referred in the main payload mapping script file as:

function CodecName() {
    this.encode = function (impactRequest) {
        var request = getImpactRequestAsJson(impactRequest);
        // ...

Similarly, we can create another util function for handling response creation in the decoder.

function formImpactResponseFromJson(decodeCtx, resources, success=true) {
    if(decodeCtx.getRequest() != null) { // uplink is a response for IMPACT request
        var corrId = decodeCtx.getRequest().getCorrelatorId();
        var resp = {
                responseCode: success? 0: 1,
                requestStatus: 0,
                response: [],
                correlatorId: corrId
        };
        var resourceObj = {"device/0/endPointClientName": client.getEndpoint()};
        resources.forEach(resource => {
            resourceObj[resource.name] = resource.value;
        });
        resp.response.push(resourceObj);
        return utils.createJsonResponse(JSON.stringify(resp));

     } else {   // uplink is an unsolicited notification message
        var resp = {details: {"device/0/endPointClientName": client.getEndpoint()}};
        resources.forEach(resource => {
            resp.details[resource.name] = resource.value;
        });
        return utils.createJsonResponse(JSON.stringify(resp));
    }
}

You can add more functions in the util file and refer it in the main codec script file. In the Script template, you can find the util script containing some more functions like buf2hex, bytes2String, string2Bytes, isBitSet. These functions are being used by sample codec scripts. You may use them if required.

When a codec function script is executed, the associated utility script is preloaded. This process is known as script chaining.

As examples,