clean up api utils
This commit is contained in:
parent
b087ea673e
commit
ce708f5209
4 changed files with 74 additions and 57 deletions
53
frontend/src/apiUtils.js
Normal file
53
frontend/src/apiUtils.js
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
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 === "sorting") {
|
||||
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-z])/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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue