UNPKG

google-ads-api

Version:

Google Ads API Client Library for Node.js

89 lines (88 loc) 3.19 kB
"use strict"; /** * JSON Rest parsing */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.decamelizeKeys = void 0; const map_obj_1 = __importDefault(require("map-obj")); const circ_json_1 = require("circ-json"); const utils_1 = require("./utils"); const fields_1 = require("./protos/autogen/fields"); const enums_1 = require("./protos/autogen/enums"); const fieldDataTypes = (0, circ_json_1.parse)(fields_1.fieldDataTypes); const decamelizeCache = new Map(); const fieldTypeCache = new Map(); const isObject = (value) => typeof value === "object" && value !== null; const decamelizeKeys = (input) => { if (!isObject(input)) { return input; } const makeMapper = (parentPath) => (key, value) => { key = cachedDecamelize(key); if (isObject(value)) { const path = parentPath === undefined ? key : `${parentPath}.${key}`; // @ts-ignore value = (0, map_obj_1.default)(value, makeMapper(path)); } else { value = cachedValueParser(key, parentPath, value); } return [key, value]; }; // @ts-ignore return (0, map_obj_1.default)(input, makeMapper()); }; exports.decamelizeKeys = decamelizeKeys; const cachedDecamelize = (key) => { const cachedResult = decamelizeCache.get(key); if (cachedResult) { return cachedResult; } const newKey = (0, utils_1.toSnakeCase)(key); decamelizeCache.set(key, newKey); return newKey; }; const cachedValueParser = (key, parentPath, value) => { let newValue = value; const fullPath = parentPath ? `${parentPath}.${key}` : key; const megaDataType = getTypeFromPath(fullPath); if (megaDataType === undefined && !fullPath.startsWith("@")) { console.warn(`No data type found for ${fullPath}`); } else if (typeof megaDataType === "object") { newValue = megaDataType[value]; } else if (megaDataType === "INT64") { newValue = Number(value); } else if (megaDataType === "ENUM") { // Some enums aren't embedded in megaDataType, so we need this fallback. // @ts-expect-error typescript doesn't like accessing items in a namespace with a string newValue = enums_1.enums[fields_1.fields.enumFields[fullPath]][value]; // e.g. enums['CampaignStatus'][ENABLED] = "2" } return newValue; }; const getTypeFromPath = (path) => { const cachedResult = fieldTypeCache.get(path); if (cachedResult) { return cachedResult; } const t = get(fieldDataTypes, path); fieldTypeCache.set(path, t); return t; }; // Copied from youmightnotneed.com const get = (obj, path) => { if (!path) return undefined; // Check if path is string or array. Regex : ensure that we do not have '.' and brackets. // Regex explained: https://regexr.com/58j0k const pathArray = path.match(/([^[.\]])+/g); if (!pathArray) return undefined; // Find value return pathArray.reduce((prevObj, key) => prevObj && prevObj[key], obj); };