products_loader.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { product } from "./product.js";
  2. export class products_loader {
  3. static async all() {
  4. const request = await fetch("/products/");
  5. const response = await request.json();
  6. return products_loader.#response_to_collection(response);
  7. }
  8. static #response_to_collection(response) {
  9. if (response.result !== "success") {
  10. return new Array();
  11. }
  12. if ("collection" in response) {
  13. return this.#list_response_to_collection(response);
  14. }
  15. return this.#single_response_to_collection(response);
  16. }
  17. static #single_response_to_collection(response) {
  18. const result = new Array();
  19. result.push(new product(response.product));
  20. return result;
  21. }
  22. static #list_response_to_collection(response) {
  23. const result = new Array();
  24. response.collection.forEach(serialized => {
  25. result.push(new product(serialized));
  26. });
  27. return result;
  28. }
  29. static async search_name(name) {
  30. return await products_loader.#search(
  31. "/product/search/name",
  32. name
  33. );
  34. }
  35. static async search_author(author) {
  36. return await products_loader.#search(
  37. "/product/search/author",
  38. author
  39. );
  40. }
  41. static async search_barcode(barcode) {
  42. return await products_loader.#search(
  43. "/product/get/barcode",
  44. barcode
  45. );
  46. }
  47. static async #search(path, parameter) {
  48. const coded = encodeURI(parameter);
  49. const request = await fetch(path + "/" + coded);
  50. const response = await request.json();
  51. return products_loader.#response_to_collection(response);
  52. }
  53. }