Michael-Gibbons / OSB

An Opinionated Full Stack Shopify App Boiler
MIT License
19 stars 2 forks source link

Build JSON request coerser for API #100

Open Michael-Gibbons opened 1 year ago

Michael-Gibbons commented 8 months ago
function coerceJSON(payload) {
  // Helper function to coerce values
  function coerceValue(value) {
    if (value === 'true') return true;
    if (value === 'false') return false;
    if (!isNaN(value)) {
      return Number.isInteger(Number(value)) ? parseInt(value) : parseFloat(value);
    }
    if (value === 'null') return null;
    if (value === 'undefined') return undefined;
    return value;
  }

  // Helper function to handle coercion for objects and arrays
  function coerceObject(obj) {
    if (Array.isArray(obj)) {
      return obj.map(item => Array.isArray(item) || (typeof item === 'object' && item !== null) ? coerceObject(item) : coerceValue(item));
    }
    if (typeof obj === 'object' && obj !== null) {
      const coercedObj = {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          coercedObj[key] = Array.isArray(obj[key]) || (typeof obj[key] === 'object' && obj[key] !== null) ? coerceObject(obj[key]) : coerceValue(obj[key]);
        }
      }
      return coercedObj;
    }
    return coerceValue(obj);
  }

  // Start coercion recursively
  return coerceObject(payload);
}

// Example usage:
const payload = {
  "booleanString": "true",
  "numberString": "42",
  "floatString": "3.14",
  "nullString": "null",
  "undefinedString": "undefined",
  "nestedObject": {
    "booleanString": "false",
    "numberString": "123",
    "floatString": "2.718",
    "nullString": "null",
    "undefinedString": "undefined",
    "array": ["1", "2", "3"]
  },
  "array": ["true", "false", "42", "3.14", "null", "undefined"],
  "nestedArray": [
    [{ "booleanString": "true", "numberString": "42" }],
    [{ "booleanString": "false", "numberString": "123" }]
  ]
};

const coercedPayload = coerceJSON(payload);
console.log(coercedPayload);