@paritydeals/node-sdk
Version:
Node.js SDK for interacting with the ParityDeals API.
65 lines • 2.87 kB
JavaScript
;
// src/utils.ts
Object.defineProperty(exports, "__esModule", { value: true });
exports.toSnakeCase = toSnakeCase;
exports.keysToSnakeCase = keysToSnakeCase;
exports.prepareSnakeCaseParams = prepareSnakeCaseParams;
/**
* Converts a camelCase or PascalCase string to snake_case.
* Examples:
* toSnakeCase("helloWorld") // "hello_world"
* toSnakeCase("HelloWorld") // "hello_world"
* toSnakeCase("CustomerID") // "customer_id"
* toSnakeCase("IPAddress") // "ip_address"
* @param str The string to convert.
* @returns The snake_cased string.
*/
function toSnakeCase(str) {
if (!str)
return str; // Handle empty or null strings
return str
// Add an underscore before any uppercase letter that is preceded by a lowercase letter or digit,
// OR before an uppercase letter that is followed by a lowercase letter (to handle acronyms like IPAddress -> ip_address).
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
.replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')
.toLowerCase();
}
/**
* Recursively converts all keys of an object (and its nested objects/arrays) from camelCase to snake_case.
* @param obj The object or array to transform.
* @returns A new object or array with snake_case keys.
*/
function keysToSnakeCase(obj) {
if (Array.isArray(obj)) {
// If it's an array, map over its elements and recursively call keysToSnakeCase
return obj.map(v => keysToSnakeCase(v));
}
else if (obj !== null && typeof obj === 'object' && obj.constructor === Object) {
// If it's a plain object, reduce its keys
return Object.keys(obj).reduce((acc, key) => {
const snakeKey = toSnakeCase(key);
acc[snakeKey] = keysToSnakeCase(obj[key]); // Recursively transform the value
return acc;
}, {}); // Initialize accumulator as an empty object
}
// If it's not an array or plain object (e.g., primitive, Date, null), return it as is
return obj;
}
/**
* Converts object keys for query parameters to snake_case and filters out null or undefined values.
* This is useful for preparing objects to be used as query parameters.
* @param params The parameters object (keys typically in camelCase).
* @returns A new object with snake_case keys and only defined (non-null, non-undefined) values.
*/
function prepareSnakeCaseParams(params) {
const snakeCaseParams = {};
for (const key in params) {
// Check if the property belongs to the object itself (not its prototype)
// and if the value is neither null nor undefined.
if (Object.prototype.hasOwnProperty.call(params, key) && params[key] !== undefined && params[key] !== null) {
snakeCaseParams[toSnakeCase(key)] = params[key]; // Value is kept as is
}
}
return snakeCaseParams;
}
//# sourceMappingURL=utils.js.map