const axios = require('axios').default;
const API_URL = 'http://127.0.0.1:3030';
const randomKey = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
/** The client that communicates with the Pod. */
class PodClient {
constructor(apiUrl = API_URL, version = 'v2', ownerKey = randomKey(64), databaseKey = randomKey(64)) {
this.apiUrl = apiUrl;
this.version = version;
this.ownerKey = ownerKey;
this.databaseKey = databaseKey;
this.url = `${this.apiUrl}/${this.version}/${this.ownerKey}`;
}
/** Test the connection with the Pod. */
async testConnection() {
await axios.get(`${this.apiUrl}/version`)
.then(res => {
console.log(`Connected, Pod version: ${res.data}`);
})
.catch(error => {
console.log(error);
});
}
/** Get an item from the Pod.
* @param {uid} uid - Get the item with this uid.
*/
async getItem(uid) {
await axios.post(`${this.url}/get_item`)
.then(res => res.data)
.catch(error => {
console.log(error);
});
}
/** Create an item in the Pod.
* @param {Item} item - The item to be created in the Pod.
* */
async createItem(item) {
try {
let data = {"databaseKey": this.databaseKey, "payload": item};
let res = await axios.post(`${this.url}/create_item`, data);
return res.status_code === 200;
} catch (error) {
console.error(error);
return false;
}
}
/** Get all items from Pod */
async getAllItems() {
let res = await axios.post(`${this.url}/get_all_items`, {
databaseKey: this.databaseKey,
payload: null
}).catch(error => {
console.log(error);
});
return res.data;
}
}
module.exports = {
PodClient: PodClient
}