devil-db
Version:
A simple way to communicate with DevilDB CMS with a js REST library
170 lines (161 loc) • 6.54 kB
JavaScript
const axios = require("axios")
class Devil {
constructor({ organization, apiKey, project }) {
this.organization = organization;
this.apiKey = apiKey;
this.project = project;
this.searchRequests = [];
}
search(collection, searchTerm) {
return new DevilRequest({ instance: this, collection: collection, search: searchTerm })
}
collection(collection) {
return new DevilRequest({ instance: this, collection: collection })
}
}
const baseEndpoint = 'https://devildb-gateway-gvwk7ffjaa-uc.a.run.app/api/public';
module.exports = Devil
module.exports.default = Devil
class DevilRequest {
constructor({ instance, collection, doc, search }) {
this.instance = instance;
this.collection = collection;
this.doc = doc;
this.pageNo = 1;
this.amountPerPage = 100;
this.search = search || '';
this.callEverything = false;
this.data;
this.q = '';
this.pendingImages = [];
}
pageNumber(pageNumber) {
this.pageNo = pageNumber;
return this;
}
perPage(perPage) {
if (this.amountPerPage != perPage) {
this.amountPerPage = perPage;
}
return this
}
everything() {
this.callEverything = true;
return this;
}
item(doc) {
if (!doc) throw ('item cant be ' + doc)
this.doc = doc;
return this;
}
query(q) {
if (!q) return this;
if (this.q) {
this.q += '+' + q
} else {
this.q = q
}
return this
}
image(key, image) {
const formData = new FormData()
formData.append("imageFile", image.selectedImage, image.name)
return new Promise((resolve, reject) => {
var url = `${baseEndpoint}/organization/${this.instance.organization}/project/${this.instance.project}/collection/${this.collection}/items/${this.doc}/image?imageSlug=${key}&key=${this.instance.apiKey}`;
axios.put(url, formData).then(imgResponse => {
resolve(imgResponse);
}).catch(err =>
reject(err))
});
}
delete() {
var url = `${baseEndpoint}/organization/${this.instance.organization}/project/${this.instance.project}/collection/${this.collection}/items/${this.doc}?key=${this.instance.apiKey}`;
return new Promise((resolve, reject) => {
axios.delete(url).then(res => resolve(res)).catch(err => reject(err))
});
}
put(data) {
for (let [key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
if (value[0]["_id"]) {
data[key] = value.map(e => { return { itemRefID: e._id } });
} else if (typeof value == "string") {
data[key] = value.map(e => { return { itemRefID: e } });
}
} else if (value.selectedImage) {
this.pendingImages.push({ slug: key, image: value })
delete data[key]
}
}
var url = `${baseEndpoint}/organization/${this.instance.organization}/project/${this.instance.project}/collection/${this.collection}/items/${this.doc}?key=${this.instance.apiKey}`;
return new Promise((resolve, reject) => {
axios.put(url, JSON.stringify(data)).then(async res => {
if (this.pendingImages.length > 0) {
var id = res.id;
await Promise.all(this.pendingImages.map(async i => {
let image = await this.item(id).image(i.slug, i.image);
return image.data;
}));
}
resolve(res);
}).catch(err =>
reject(err))
});
}
sort(field, order) {
this.sortField = field;
this.sortOrder = order || "";
return this
}
post(data) {
for (let [key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
if (value[0]["_id"]) {
data[key] = value.map(e => { return { itemRefID: e._id } });
} else if (typeof value == "string") {
data[key] = value.map(e => { return { itemRefID: e } });
}
} else if (value.selectedImage) {
this.pendingImages.push({ slug: key, image: value })
delete data[key]
}
}
return new Promise((resolve, reject) => {
var url = `${baseEndpoint}/organization/${this.instance.organization}/project/${this.instance.project}/collection/${this.collection}/items?key=${this.instance.apiKey}`;
axios.post(url, data)
.then(res => {
if (this.pendingImages.length > 0) {
this.item(res.data.id);
Promise.all(this.pendingImages.map(async i => {
var img = await this.image(i.slug, i.image)
res.data[i.slug] = img.data;
return img;
})).then(() => { resolve(res); });
}
})
.catch((error) => {
reject(error);
});
})
}
get() {
return new Promise(async (resolve, reject) => {
var query = this.q || this.search ? '&query=' + this.search + (this.q && this.search ? '+' : '') + this.q : '';
var item = this.doc ? '/' + this.doc : '';
var sort = this.sortField ? '&sort=' + this.sortField : '';
var sortOrder = this.sortOrder ? '&order=' + this.sortOrder : '';
var callEverything = this.callEverything ? `&everything=${this.callEverything}` : '';
var search = this.search ? 'search' : 'items';
var url = `${baseEndpoint}/organization/${this.instance.organization}/project/${this.instance.project}/collection/${this.collection}/${search}${item}?pageNumber=${this.pageNo}&perPage=${this.amountPerPage}&key=${this.instance.apiKey}${callEverything}${query}${sort}${sortOrder}`
await axios.get(url, true).then((res) => {
if (res.status >= 200 && res.status < 400) {
resolve(res)
} else {
reject(res)
}
}).catch((err) => {
reject()
});
});
}
}