The CreatorCon Call for Content is officially open! Get started here.

I am not able to pass array of values in the query parameter, my scripting is working fine with one

ahmed786
Tera Contributor
var id = ["e99b1e93c3a312103d3e1612b40131a0", "723dda83c327d2103d3e1612b40131ca"];

 

// Join the ID array into a string with commas
var idParam = id.join(',');

 

// Construct the query parameters with the IN operator
var queryParams = {
    "sys_idIN": idParam
};

 

var tmfServiceOrderAPIUtil = new sn_ind_tmt_orm.TMFServiceOrderGetAPIUtil();

 

// Make sure to modify the URL if needed (e.g., adding any required query params)
var response = tmfServiceOrderAPIUtil.processListServiceOrder(queryParams, 'https://dev186817.service-now.com/api/sn_ind_tmt_orm/serviceorder');

 

var statusCode = response.status;  
var responseBody = JSON.stringify(response.details);

 

if (statusCode == 200) {
    gs.info("Request succeeded, response: " + responseBody);
} else {
    gs.error("Request failed with status code: " + statusCode + " and message: " + responseBody);
}
 
=============================================================
 
var id = ["e99b1e93c3a312103d3e1612b40131a0", "723dda83c327d2103d3e1612b40131ca"];
var queryParams = {
    "id": id  
};
var tmfServiceOrderAPIUtil = new sn_ind_tmt_orm.TMFServiceOrderGetAPIUtil();
var response = tmfServiceOrderAPIUtil.processListServiceOrder(queryParams, 'https://dev186817.service-now.com/api/sn_ind_tmt_orm/serviceorder');

var statusCode = response.status;  
var responseBody = JSON.stringify(response.details);


if (statusCode == 200) {
    gs.info("Request succeeded, response: " + responseBody);
} else {
    gs.error("Request failed with status code: " + statusCode + " and message: " + responseBody);
}
==================================================
Following error i am getting when i use the above code, from the rest API explorer i don't find the option to construct the above one and test.  Can some one help me 
Request failed with status code: 404 and message: {"code":60,"reason":"Resource not found","message":"No Record found for given filter criteria","details":[{"message":"No Record found for given filter criteria","datapath":""}]}
10 REPLIES 10

Ankur Bawiskar
Tera Patron
Tera Patron

@ahmed786 

how it's working with 1 sysId?

share that and also share script include code where it's working for 1 sysId

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

var id = ["723dda83c327d2103d3e1612b40131ca"];
var queryParams = {
    "id": id  
};
var tmfServiceOrderAPIUtil = new sn_ind_tmt_orm.TMFServiceOrderGetAPIUtil();
var response = tmfServiceOrderAPIUtil.processListServiceOrder(queryParams, 'https://dev186817.service-now.com/api/sn_ind_tmt_orm/serviceorder');

var statusCode = response.status;  
var responseBody = JSON.stringify(response.details);


if (statusCode == 200) {
    gs.info("Request succeeded, response: " + responseBody);
} else {
    gs.error("Request failed with status code: " + statusCode + " and message: " + responseBody);
}, if i have one element its working when i have multiple element its getting failed while parsing the queryParams
 

Hi @ahmed786 

It depends on how queryParams is used in the script include. If you have access to view the script jnclude, please share the function block script for 'processListServiceOrder'

var TMFServiceOrderGetAPIUtil = Class.create();
TMFServiceOrderGetAPIUtil.prototype = Object.extendsObject(sn_tmt_core.BaseAPIUtil, {
    initialize: function() {
        sn_tmt_core.BaseAPIUtil.prototype.initialize.call(this, TMFOrderAPIConstants.SERVICE_ORDER_LEVEL_OF_LOGGING);
        this.tmfCommonOrderAPIUtil = new TMFCommonOrderAPIUtil();
        this.tsmOpenAPIUtil = new sn_tmt_core.BaseAPIUtil();
        this.apiCoreUtil = new sn_tmt_core.APICoreUtil();
        this.serviceOrderProcessor = new ServiceOrderProcessor();
        this.tmfValidationUtil = new sn_ind_tmt_orm.TMFValidationUtil();
    },

    processGetOrder: function(id, queryParams) {
        try {
            // Customized validation 'validateGetRequest', defaults to true.
            if (!this.tmfValidationUtil.isValidOrderID(id, Constants.ORDER_CATE_SERVICE, this.response, Constants.ENCODED_QUERY) || !this.serviceOrderProcessor.validateGetRequest(id, this.response))
                return this.response;

            var serviceOrderTransformMap = new CustomerOrderTransformMap(queryParams, Constants.TABLE_SERVICE_ORDER);
            var filters = serviceOrderTransformMap.transformQueryParams();

            var serviceOrderGr = OrderDAO.queryRecordByID(id, Constants.ORDER_CATE_SERVICE, filters);
            if (!serviceOrderGr.hasNext())
                return this.response = this.returnErrorMessage(sn_tmt_core.Constants.MESSAGES.INVALID_FILTER_CONDITION);

            // Service order response
            var serviceOrdObj = this.prepareGetOrderResponse(serviceOrderGr);
            // Parse response upon transformations
            serviceOrdObj = this.serviceOrderProcessor.transformServiceOrdObjJSON(serviceOrdObj);
            // Filtering by Fields
            var filterAPI = new sn_tmt_core.FilterAPI();
            var fields = serviceOrderTransformMap.getFields();
            var filteredRes = filterAPI.filterObject(fields, serviceOrdObj);
            this.response.details = filteredRes;
            this.response.status = sn_tmt_core.Constants.STATUS_CODES.OK;
        } catch (ex) {
            var details = [];
            details.push(this.apiCoreUtil.getErrorDetailsObj(ex.message + '', ''));
            var errorObj = this.apiCoreUtil.getErrorObj(sn_tmt_core.Constants.ERROR_CODES.INTERNAL_ERROR, sn_tmt_core.Constants.MESSAGES.GET_ERROR, sn_tmt_core.Constants.MESSAGES.GET_ERROR);
            errorObj.details = details;
            this.response.details = errorObj;
        }
        return this.response;
    },

    prepareGetOrderResponse: function(serviceOrdGr, isGetAPI) {
        var serviceOrdObj = new sn_tmt_core.BaseObject();
        if (gs.nil(isGetAPI))
            serviceOrdGr.next();
        serviceOrdObj.setValue('id', serviceOrdGr.getValue('sys_id'));
        serviceOrdObj.setValue('ponr', serviceOrdGr.getDisplayValue('ponr'));
        serviceOrdObj.setValue('href', this.tmfCommonOrderAPIUtil.getURL(serviceOrdGr.getValue('sys_id')));
        if (!gs.nil(serviceOrdGr.getValue("order_currency")))
            serviceOrdObj.setValue('orderCurrency', serviceOrdGr.getValue('order_currency'));

        if (!gs.nil(serviceOrdGr.getValue("priority")))
            serviceOrdObj.setValue('priority', parseInt(serviceOrdGr.getValue('priority')));

        if (!gs.nil(serviceOrdGr.getValue("actual_end_date")))
            serviceOrdObj.setValue('completionDate', this.tsmOpenAPIUtil.transformToISODate(serviceOrdGr.getDisplayValue('actual_end_date')));

        if (!gs.nil(serviceOrdGr.getValue("expected_end_date")))
            serviceOrdObj.setValue('expectedCompletionDate', this.tsmOpenAPIUtil.transformToISODate(serviceOrdGr.getDisplayValue('expected_end_date')));

        if (!gs.nil(serviceOrdGr.getValue("order_date")))
            serviceOrdObj.setValue('orderDate', this.tsmOpenAPIUtil.transformToISODate(serviceOrdGr.getDisplayValue('order_date')));

        if (!gs.nil(serviceOrdGr.getValue("expected_end_date")))
            serviceOrdObj.setValue('requestedCompletionDate', this.tsmOpenAPIUtil.transformToISODate(serviceOrdGr.getDisplayValue('expected_end_date')));

        if (!gs.nil(serviceOrdGr.getValue("expected_start_date")))
            serviceOrdObj.setValue('requestedStartDate', this.tsmOpenAPIUtil.transformToISODate(serviceOrdGr.getDisplayValue('expected_start_date')));

        if (!gs.nil(serviceOrdGr.getValue("committed_due_date")))
            serviceOrdObj.setValue('committedDueDate', this.tsmOpenAPIUtil.transformToISODate(serviceOrdGr.getDisplayValue('committed_due_date')));

        if (!gs.nil(serviceOrdGr.comments.getJournalEntry(-1)))
            serviceOrdObj.setValue('note', this.tmfCommonOrderAPIUtil.getNotes(serviceOrdGr));

        var orderLineItemList = this.getServiceOrderLineItem(serviceOrdGr);
        if (orderLineItemList.length > 0)
            serviceOrdObj.setValue('serviceOrderItem', orderLineItemList);

        var relatedParty = this.tmfCommonOrderAPIUtil.getRelatedParty(serviceOrdGr);
        if (relatedParty.length > 0)
            serviceOrdObj.setValue('relatedParty', relatedParty);

        serviceOrdObj.setValue('state', serviceOrdGr.getValue('state'));
        serviceOrdObj.setValue('version', serviceOrdGr.getValue('version'));
        serviceOrdObj.setValue('@type', TMFOrderAPIConstants.TYPE_SERVICE_ORDER);

        // Customize Order object as per requirement.
        serviceOrdObj = this.serviceOrderProcessor.transformGetOrderResponse(serviceOrdObj, serviceOrdGr);
        return serviceOrdObj;
    },

    prepareListServiceOrder: function(serviceOrderGr) {
        var serviceOrderList = [];
        while (serviceOrderGr.next()) {
            var productOrderObj = this.prepareGetOrderResponse(serviceOrderGr, false);
            serviceOrderList.push(productOrderObj);
        }
        return serviceOrderList;
    },

    /*
     * processListServiceOrder : Retrieves the service orders and displays in JSON Format.
     * It Supports
     * 1) Filtering by fields and
     * 2) Fitlering by query Conditions and
     * 3) Pagination
     *
     */
    processListServiceOrder: function(queryParams, requestURL) {
        try {
            var serviceOrderTransformMap = new CustomerOrderTransformMap(queryParams, Constants.TABLE_SERVICE_ORDER);
            var filters = serviceOrderTransformMap.transformQueryParams();

            //Invalid Offset
            if (serviceOrderTransformMap.isInvalidOffset())
                return this.response = this.returnErrorMessage(sn_tmt_core.Constants.MESSAGES.INVALID_OFFSET_MESSAGE, sn_tmt_core.Constants.ERROR_CODES.INTERNAL_ERROR, sn_tmt_core.Constants.MESSAGES.OFFSET_INVALID_REASON);

            //Invalid Limit
            if (serviceOrderTransformMap.isInvalidLimit())
                return this.response = this.returnErrorMessage(sn_tmt_core.Constants.MESSAGES.INVALID_LIMIT_MESSAGE, sn_tmt_core.Constants.ERROR_CODES.INTERNAL_ERROR, sn_tmt_core.Constants.MESSAGES.LIMIT_INVALID_REASON);

            var offset = gs.nil(serviceOrderTransformMap.getOffset()) ? 0 : serviceOrderTransformMap.getOffset();
            var limit = serviceOrderTransformMap.getLimit();

            //Checking the Limit exceeds Maximum Limit
            if (!gs.nil(limit)) {
                if (limit > sn_prd_pm_adv.Constants.PAGINATION.MAX_LIMIT)
                    return this.response = this.returnErrorMessage(sn_tmt_core.Constants.MESSAGES.INVALID_PAGE_LIMIT, sn_tmt_core.Constants.ERROR_CODES.INTERNAL_ERROR, sn_tmt_core.Constants.MESSAGES.LIMIT_INVALID);
            }

            var serviceOrderGr = OrderDAO.queryAllRecords(filters, Constants.ORDER_CATE_SERVICE, offset, limit);
            if (!serviceOrderGr.hasNext())
                return this.response = this.returnErrorMessage(sn_tmt_core.Constants.MESSAGES.INVALID_FILTER_CONDITION);

            var totalCount = this.getTotalRecordCount(serviceOrderGr);
            this.request.setValues({
                'url': requestURL,
                'recordCount': totalCount,
                'queryParams': serviceOrderTransformMap.getQueryStringforPagination(),

            });

            //Retrieving Service Orders
            var serviceOrderObjs = this.prepareListServiceOrder(serviceOrderGr);

            //Filtering by fields
            var filterAPI = new sn_tmt_core.FilterAPI();
            var fields = serviceOrderTransformMap.getFields();
            var filteredRes = filterAPI.filterObjects(fields, serviceOrderObjs);

            //Setting the pagination response headers
            this.response.setValue('details', filteredRes);
            if (!gs.nil(totalCount)) {
                this.response.setValues({
                    'totalCount': totalCount,
                    'contentRange': this.getContentRange(offset, limit),
                    'status': this.getStatus(limit),
                    'links': this.getLinks(offset, limit)
                });
            }

        } catch (ex) {
            var details = [];
            details.push(this.getErrorDetailsObj(ex.message + '', ''));
            var errorObj = this.retrieveErrorObject(sn_tmt_core.Constants.ERROR_CODES.INTERNAL_ERROR, sn_tmt_core.Constants.MESSAGES.GET_ERROR, sn_tmt_core.Constants.MESSAGES.GET_ERROR, details);
            this.response.setValue('details', errorObj);
        }
        return this.response;
    },

    getServiceOrderLineItem: function(customerOrder) {
        var orderLineItemList = [];
        var orderLineItemGr = OrderLineItemDAO.queryOrderLineItems(customerOrder);
        while (orderLineItemGr.next()) {
            var orderLineItemObj = new sn_tmt_core.BaseObject();
            var orderLineID = gs.nil(orderLineItemGr.getValue(Constants.EXTERNAL_ID)) ? orderLineItemGr.getValue("sys_id") : orderLineItemGr.getValue(Constants.EXTERNAL_ID);
            orderLineItemObj.setValue('id', orderLineID);
            if (!gs.nil(orderLineItemGr.getValue("committed_due_date")))
                orderLineItemObj.setValue('committedDueDate', this.tsmOpenAPIUtil.transformToISODate(orderLineItemGr.getDisplayValue("committed_due_date")));
            orderLineItemObj.setValue('ponr', orderLineItemGr.getDisplayValue('ponr'));
            if (!gs.nil(orderLineItemGr.getValue("quantity")))
                orderLineItemObj.setValue('quantity', parseInt(orderLineItemGr.getValue("quantity")));
            if (!gs.nil(orderLineItemGr.getValue("action")) && orderLineItemGr.getValue("action") == TMFOrderAPIConstants.LINE_ITEM_ACTION.ADD) {
                var extPrdInvtArr = this.tmfCommonOrderAPIUtil.getExternalInventoryIds(orderLineItemGr);
                if (!gs.nil(extPrdInvtArr) && extPrdInvtArr.length > 0) {
                    orderLineItemObj.setValue('externalProductInventory', extPrdInvtArr);
                }
            }
            if (!gs.nil(orderLineItemGr.getValue("priority")))
                orderLineItemObj.setValue('priority', parseInt(orderLineItemGr.getValue("priority")));

            if (!gs.nil(orderLineItemGr.getValue("action")))
                orderLineItemObj.setValue('action', orderLineItemGr.getValue("action") == TMFOrderAPIConstants.ORDER_TYPE.DELETE ? TMFOrderAPIConstants.LINE_ITEM_ACTION.DELETE : orderLineItemGr.getValue("action"));
            if (!gs.nil(orderLineItemGr.getValue("action_reason")))
                orderLineItemObj.setValue('actionReason', orderLineItemGr.getValue('action_reason'));
            // Customize service object as per requirement.
            var serviceObj = this.getServiceObj(orderLineItemGr);
            serviceObj = this.serviceOrderProcessor.transformServiceObj(serviceObj, orderLineItemGr);
            if (!global.JSUtil.isEmpty(serviceObj))
                orderLineItemObj.setValue('service', serviceObj);

            if (!gs.nil(orderLineItemGr.getValue('location')))
                orderLineItemObj.setValue('place', this.tmfCommonOrderAPIUtil.getLocation(orderLineItemGr));

            // Customize order line item contact as per requirement.
            var relatedPartyCustomerLineItem = this.tmfCommonOrderAPIUtil.getRelatedPartyCustomerLineItem(orderLineItemGr);
            relatedPartyCustomerLineItem = this.serviceOrderProcessor.transformRelatedPartyCustomerLineItem(relatedPartyCustomerLineItem, orderLineItemGr);
            if (relatedPartyCustomerLineItem.length > 0)
                orderLineItemObj.setValue('relatedParty', relatedPartyCustomerLineItem);

            //Customize order line item relationship as per requirement.
            var orderItemRelationship = this.tmfCommonOrderAPIUtil.getOrderItemRelationship(orderLineItemGr);
            orderItemRelationship = this.serviceOrderProcessor.transformOrderItemRelationship(orderItemRelationship, orderLineItemGr);
            if (orderItemRelationship.length > 0)
                orderLineItemObj.setValue('orderRelationship', orderItemRelationship);

            orderLineItemObj.setValue('state', orderLineItemGr.getValue('state'));
            orderLineItemObj.setValue('version', orderLineItemGr.getValue('version'));
            orderLineItemObj.setValue('@type', TMFOrderAPIConstants.TYPE_SERVICE_ORDER_ITEM);

            // Customize order line item object as per requirement.
            orderLineItemObj = this.serviceOrderProcessor.transformGetOrdLineItmResponse(orderLineItemObj, orderLineItemGr);
            orderLineItemList.push(orderLineItemObj);
        }
        return orderLineItemList;
    },

    getServiceObj: function(orderLineItemGr) {
        var service = new sn_tmt_core.BaseObject();
        service.setValue('@type', TMFOrderAPIConstants.TYPE_SERVICE);

        if (!gs.nil(orderLineItemGr.getValue('sold_product'))) {
            var serviceId = gs.nil(orderLineItemGr.sold_product.sn_prd_invt_external_id) ? orderLineItemGr.getValue('sold_product') : orderLineItemGr.sold_product.sn_prd_invt_external_id + '';
            service.setValue('id', serviceId);
        }

        if (!gs.nil(orderLineItemGr.getValue('sold_product')))
            service.setValue('state', orderLineItemGr.sold_product.state + '');
        else
            service.setValue('state', null);

        service.setValue('serviceType', orderLineItemGr.service_specification.specification_type + '');

        // Customize order characteristic as per requirement.
        var characteristicArray = this.getServiceCharacteristics(orderLineItemGr);
        characteristicArray = this.serviceOrderProcessor.transformServiceCharacteristics(characteristicArray, orderLineItemGr);
        if (characteristicArray.length > 0)
            service.setValue('serviceCharacteristic', characteristicArray);

        // Customize service spec as per requirement.
        var serviceSpecificationObj = this.getServiceSpecification(orderLineItemGr);
        serviceSpecificationObj = this.serviceOrderProcessor.transformServiceSpecification(serviceSpecificationObj, orderLineItemGr);
        service.setValue('serviceSpecification', serviceSpecificationObj);
        var serviceRelationship = this.tmfCommonOrderAPIUtil.getInventoryRelationship(orderLineItemGr.getValue('sys_id'));
        serviceRelationship = this.serviceOrderProcessor.transformInvtRelationship(serviceRelationship, orderLineItemGr); // Customize Order Line Related Items as per requirement.
        if (serviceRelationship.length > 0)
            service.setValue('serviceRelationship', serviceRelationship);
        return service;
    },

    getServiceCharacteristics: function(orderLineItemGr) {
        var characteristicArray = [];
        var characteristics = OrderCharacteristicValueDAO.queryAllBySpecification(orderLineItemGr, false);
        while (characteristics.next()) {
            var characteristicObj = this.tmfCommonOrderAPIUtil.getCharacteristicArray(characteristics);
            characteristicArray.push(characteristicObj);
        }
        return characteristicArray;
    },

    getServiceSpecification: function(orderLineItemGr) {
        var serviceSpecificationObj = new sn_tmt_core.BaseObject();
        if (!gs.nil(orderLineItemGr.getValue('service_specification'))) {
            var serviceSpecID = gs.nil(orderLineItemGr.service_specification.external_id) ? orderLineItemGr.service_specification.initial_version + '' : orderLineItemGr.service_specification.external_id + '';
            serviceSpecificationObj.setValue('id', serviceSpecID);
            serviceSpecificationObj.setValue('name', orderLineItemGr.service_specification.name + '');
            serviceSpecificationObj.setValue('version', orderLineItemGr.service_specification.external_version + '');
            serviceSpecificationObj.setValue('internalVersion', orderLineItemGr.service_specification.version + '');
            serviceSpecificationObj.setValue('internalId', orderLineItemGr.service_specification.initial_version + '');
            serviceSpecificationObj.setValue('@type', TMFOrderAPIConstants.TYPE_SERVICE_SPECIFICATION);
        }
        return serviceSpecificationObj;
    },

    type: 'TMFServiceOrderGetAPIUtil'
});
======================================================
 
var CustomerOrderTransformMapOOB = Class.create();
CustomerOrderTransformMapOOB.prototype = {
    initialize: function(filteringConditions, tableName) {
        this.filteringConditions = filteringConditions;
        this.tsmOpenAPIUtil = new sn_tmt_core.BaseAPIUtil();
        var customerOrderTransformMap = TMFOrderAPIConstants.TRANSFORM_MAP.hasOwnProperty(tableName) ? TMFOrderAPIConstants.TRANSFORM_MAP[tableName] : [];
        this.filterTransformMap = new sn_tmt_core.FilterTransformMap(tableName, customerOrderTransformMap);
    },

    getObject: function() {
        return this.filterTransformMap.getBaseObject();
    },

    //orderDate -> order_date value converted from ISO to Glide Date
    transformOrderDateToGlideDate: function(filters) {
        if (gs.nil(filters))
            return '';
        var filterKey = 'orderDate';
        var filterKeyReplaceWith = 'order_date';
        var filterStringArray = filters.toString().split('&');
        for (var count = 0; count < filterStringArray.length; count++) {
            var eachQueryString = filterStringArray[count].toString();
            if (eachQueryString.indexOf(filterKey) >= 0) {
                var orderTimeISOFormat = this.filterTransformMap.getQueryStringValue(this.filteringConditions, filterKey);
                orderTimeISOFormat = orderTimeISOFormat.toString().replace(/'/g, '');
                var choiceArr = [];
                var queryString = filterKeyReplaceWith;
                var choices = orderTimeISOFormat.toString().split(',');
                for (var choiceCount = 0; choiceCount < choices.length; choiceCount++) {
                    var choice = this.tsmOpenAPIUtil.transformISODateToGlideDateTime(choices[choiceCount], Constants.SIMPLE_DATE_FORMAT);
                    //GlideRecord further updates the value of date obtained from above method before storing, hence required for filtering correctly
                    //for eg: 2020-05-03 08:13:59 from above transformISODateToGlideDateTime() changes to 2020-05-03 15:13:59 below
                    var orderGr = new GlideRecordSecure(Constants.TABLE_CUSTOMER_ORDER);
                    orderGr.order_date = choice;
                    choiceArr.push(orderGr.getValue('order_date'));
                }
                var operator = choiceArr.length > 1 ? 'IN' : '=';
                eachQueryString = queryString.concat(operator, choiceArr.join(','));
            }
            filterStringArray[count] = eachQueryString;
        }
        return filterStringArray.join('&');
    },

    transformQueryParams: function() {
        var filters = this.filterTransformMap.generateQueryStringByExcludingParameters(this.filteringConditions, ['fields', 'offset', 'limit']);
        filters = this.transformOrderDateToGlideDate(filters);
        filters = this.filterTransformMap.transformQueryParams(filters);
        return filters;
    },

    getFields: function() {
        return this.filterTransformMap.getQueryStringValue(this.filteringConditions, 'fields');
    },

    getOffset: function() {
        return this.filterTransformMap.getQueryStringValue(this.filteringConditions, 'offset');
    },

    getLimit: function() {
        return this.filterTransformMap.getQueryStringValue(this.filteringConditions, 'limit');
    },

    getQueryStringforPagination: function() {
        var filters = this.filterTransformMap.generateQueryStringByExcludingParameters(this.filteringConditions, ['offset', 'limit']);
        return filters;
    },

    isInvalidOffset: function() {
        return this.filterTransformMap.isNaNProperty(this.filteringConditions, 'offset');
    },

    isInvalidLimit: function() {
        return this.filterTransformMap.isNaNProperty(this.filteringConditions, 'limit');
    },


    type: 'CustomerOrderTransformMapOOB'
};