Files
2026-01-08 23:23:48 +02:00

112 lines
2.4 KiB
JavaScript

import axios from "axios";
class Errors {
constructor(data) {
this.data = data ?? [];
}
first() {
return this.data[0] ?? null;
}
all() {
return this.data;
}
isEmpty() {
return this.data.length === 0;
}
isNotEmpty() {
return !this.isEmpty();
}
}
function makeErrors(errs) {
return new Errors(errs);
}
export function post(url, postData, callback) {
axios
.post(url, postData)
.then((res) => {
if (res.data.redirect !== undefined) {
// Turbo.visit(link(res.data.redirect));
return;
}
const errors = makeErrors(res.data?.errors ?? []);
if (errors.isNotEmpty()) {
callback?.(null, errors);
} else {
callback?.(res.data, errors);
}
})
.catch((err) => {
const errors = makeErrors(["something went wrong"]);
callback?.(null, errors);
});
}
export function get(url, urlParams, callback) {
let params = url.endsWith("query")
? {
params: { query: JSON.stringify(urlParams) },
paramsSerializer: (params) => serializeParams(params),
}
: {
params: urlParams,
};
return axios
.get(url, params)
.then((res) => {
callback(res.data);
})
.catch((err) => {
console.log(err);
let errors = makeErrors(["something went wrong"]);
if (!err) {
errors = makeErrors([]);
}
callback(null, errors);
});
}
function serializeParams(obj, prefix = "") {
const params = [];
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
const paramKey = prefix ? `${prefix}[${key}]` : key;
if (
typeof value === "object" &&
value !== null &&
!Array.isArray(value)
) {
// Nested object
params.push(serializeParams(value, paramKey));
} else if (Array.isArray(value)) {
// Array
value.forEach((item, index) => {
if (typeof item === "object" && item !== null) {
params.push(serializeParams(item, `${paramKey}[${index}]`));
} else {
params.push(
`${encodeURIComponent(`${paramKey}[${index}]`)}=${encodeURIComponent(item)}`,
);
}
});
} else {
// Simple value
params.push(
`${encodeURIComponent(paramKey)}=${encodeURIComponent(value)}`,
);
}
}
}
return params.flat().join("&");
}