All files / engine/Source/Core objectToQuery.js

100% Statements 15/15
83.33% Branches 5/6
100% Functions 1/1
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                                    8490x 1x       8489x 8489x 12040x 12040x   12040x 12040x 9x 24x     12031x           8489x           8489x      
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";
 
/**
 * Converts an object representing a set of name/value pairs into a query string,
 * with names and values encoded properly for use in a URL.  Values that are arrays
 * will produce multiple values with the same name.
 * @function objectToQuery
 *
 * @param {object} obj The object containing data to encode.
 * @returns {string} An encoded query string.
 *
 *
 * @example
 * const str = Cesium.objectToQuery({
 *     key1 : 'some value',
 *     key2 : 'a/b',
 *     key3 : ['x', 'y']
 * });
 *
 * @see queryToObject
 * // str will be:
 * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
 */
function objectToQuery(obj) {
  //>>includeStart('debug', pragmas.debug);
  if (!defined(obj)) {
    throw new DeveloperError("obj is required.");
  }
  //>>includeEnd('debug');
 
  let result = "";
  for (const propName in obj) {
    Eif (obj.hasOwnProperty(propName)) {
      const value = obj[propName];
 
      const part = `${encodeURIComponent(propName)}=`;
      if (Array.isArray(value)) {
        for (let i = 0, len = value.length; i < len; ++i) {
          result += `${part + encodeURIComponent(value[i])}&`;
        }
      } else {
        result += `${part + encodeURIComponent(value)}&`;
      }
    }
  }
 
  // trim last &
  result = result.slice(0, -1);
 
  // This function used to replace %20 with + which is more compact and readable.
  // However, some servers didn't properly handle + as a space.
  // https://github.com/CesiumGS/cesium/issues/2192
 
  return result;
}
export default objectToQuery;