custom_ui/frontend/src/apiUtils.js
2025-12-16 11:57:37 -06:00

54 lines
1.5 KiB
JavaScript

class ApiUtils {
static toSnakeCaseObject(obj) {
console.log("Converting to snake case:", obj);
const newObj = Object.entries(obj).reduce((acc, [key, value]) => {
const snakeKey = key.replace(/[A-Z]/g, (match) => "_" + match.toLowerCase());
if (key === "sortings") {
value = value
? value.map((item) => {
const [field, order] = item;
const snakeField = field.replace(
/[A-Z]/g,
(match) => "_" + match.toLowerCase(),
);
return [snakeField, order];
})
: value;
}
if (Array.isArray(value)) {
value = value.map((item) => {
return Object.prototype.toString.call(item) === "[object Object]"
? this.toSnakeCaseObject(item)
: item;
});
} else if (Object.prototype.toString.call(value) === "[object Object]") {
value = this.toSnakeCaseObject(value);
}
acc[snakeKey] = value;
return acc;
}, {});
return newObj;
}
static toCamelCaseObject(obj) {
const newObj = Object.entries(obj).reduce((acc, [key, value]) => {
const camelKey = key.replace(/_([a-zA-Z0-9])/g, (match, p1) => p1.toUpperCase());
// check if value is an array
if (Array.isArray(value)) {
value = value.map((item) => {
return Object.prototype.toString.call(item) === "[object Object]"
? this.toCamelCaseObject(item)
: item;
});
} else if (Object.prototype.toString.call(value) === "[object Object]") {
value = this.toCamelCaseObject(value);
}
acc[camelKey] = value;
return acc;
}, {});
return newObj;
}
}
export default ApiUtils;