pod/client.js

  1. const axios = require('axios').default;
  2. const API_URL = 'http://127.0.0.1:3030';
  3. const randomKey = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
  4. /** The client that communicates with the Pod. */
  5. class PodClient {
  6. constructor(apiUrl = API_URL, version = 'v2', ownerKey = randomKey(64), databaseKey = randomKey(64)) {
  7. this.apiUrl = apiUrl;
  8. this.version = version;
  9. this.ownerKey = ownerKey;
  10. this.databaseKey = databaseKey;
  11. this.url = `${this.apiUrl}/${this.version}/${this.ownerKey}`;
  12. }
  13. /** Test the connection with the Pod. */
  14. async testConnection() {
  15. await axios.get(`${this.apiUrl}/version`)
  16. .then(res => {
  17. console.log(`Connected, Pod version: ${res.data}`);
  18. })
  19. .catch(error => {
  20. console.log(error);
  21. });
  22. }
  23. /** Get an item from the Pod.
  24. * @param {uid} uid - Get the item with this uid.
  25. */
  26. async getItem(uid) {
  27. await axios.post(`${this.url}/get_item`)
  28. .then(res => res.data)
  29. .catch(error => {
  30. console.log(error);
  31. });
  32. }
  33. /** Create an item in the Pod.
  34. * @param {Item} item - The item to be created in the Pod.
  35. * */
  36. async createItem(item) {
  37. try {
  38. let data = {"databaseKey": this.databaseKey, "payload": item};
  39. let res = await axios.post(`${this.url}/create_item`, data);
  40. return res.status_code === 200;
  41. } catch (error) {
  42. console.error(error);
  43. return false;
  44. }
  45. }
  46. /** Get all items from Pod */
  47. async getAllItems() {
  48. let res = await axios.post(`${this.url}/get_all_items`, {
  49. databaseKey: this.databaseKey,
  50. payload: null
  51. }).catch(error => {
  52. console.log(error);
  53. });
  54. return res.data;
  55. }
  56. }
  57. module.exports = {
  58. PodClient: PodClient
  59. }