@mee4dy/crud
Version:
Create a backend and frontend in 5 minutes! With our powerful full stack crud system, customize it to suit you.
88 lines (87 loc) • 2.3 kB
JavaScript
import * as n from "lodash";
import a from "qs";
import h from "axios";
import { ORM as d } from "../orm/orm.js";
import "deep-object-diff";
class f {
constructor(t) {
this.state = {
loading: !1
}, this.pk = t.pk || "id", this.endpoints = t.endpoints, this.orm = t.orm || !0, this.http = {
baseURL: void 0,
headers: {},
timeout: void 0,
abort: !0,
...t.http || {}
}, this.axios = h.create({
baseURL: this.http.baseURL,
headers: this.http.headers,
timeout: this.http.timeout
});
}
async fetch(t) {
var e, s;
const i = this.getEndpoint(
"fetch"
/* fetch */
);
this.setLoading(!0), this.http.abort && (this.abortController && this.abortController.abort(), this.abortController = new AbortController());
try {
const o = await this.axios.get(i, {
signal: this.abortController.signal,
params: t,
paramsSerializer: (r) => a.stringify(r, { arrayFormat: "brackets" })
});
return this.prepareItems(((s = (e = o == null ? void 0 : o.data) == null ? void 0 : e.data) == null ? void 0 : s.items) || []);
} catch (o) {
throw o;
} finally {
this.setLoading(!1);
}
}
async create(t) {
const i = this.getEndpoint(
"create"
/* create */
), e = await this.axios.post(i, {
data: t
});
return e == null ? void 0 : e.data;
}
async update(t, i) {
const e = this.getEndpoint("update", t), s = await this.axios.post(e, {
pk: t,
data: i
});
return s == null ? void 0 : s.data;
}
async delete(t) {
const i = this.getEndpoint("delete", t);
return await this.axios.post(i, {
pk: t
});
}
getEndpoint(t, i) {
let e = this.endpoints[t];
if (!e)
throw new Error("Endpoint fetch is not found!");
return i && (e = e.split(":pk").join(i.toString())), e;
}
setLoading(t) {
this.state.loading = t;
}
prepareItems(t) {
if (this.orm) {
const i = n.cloneDeep(t);
return new d(i, this.pk, {
update: ({ pk: s, data: o, level: r }) => this.update(s, o),
delete: ({ pk: s, level: o }) => this.delete(s)
}).getItems();
}
return t;
}
}
export {
f as CrudClient
};
//# sourceMappingURL=index.js.map