database.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { import_process_fail } from "./import_process_fail.js";
  2. import { product_base } from "./product_base";
  3. export class database {
  4. #content;
  5. #processed;
  6. #on_skip;
  7. constructor(content) {
  8. this.#content = content
  9. this.#processed = new Map();
  10. this.#on_skip = null;
  11. }
  12. #append(target) {
  13. if (this.#processed.has(target.barcode)) {
  14. this.#processed.get(target.barcode).stock_count += 1;
  15. return;
  16. }
  17. this.#processed.set(target.barcode, target)
  18. }
  19. #validate(target) {
  20. if (!("id" in target)) {
  21. throw new Error("One of item has no ID.");
  22. }
  23. if (!("title" in target)) {
  24. throw new Error("Product " + target.barcode + " has no title.")
  25. }
  26. if (!("author" in target)) {
  27. throw new Error("Product " + target.barcode + " has no author.")
  28. }
  29. }
  30. #convert(target) {
  31. this.#validate(target);
  32. const product = new product_base();
  33. product.name = target.title;
  34. product.description = "";
  35. product.author = target.author;
  36. product.stock_count = 1;
  37. product.barcode = target.id;
  38. return product;
  39. }
  40. on_skip(target) {
  41. this.#on_skip = target;
  42. return this;
  43. }
  44. process() {
  45. this.#processed.clear();
  46. if (!(this.#content instanceof Array)) {
  47. throw new Error("Database woud be array of objects.")
  48. }
  49. this.#content.forEach(count => {
  50. try {
  51. const product = this.#convert(count);
  52. this.#append(product);
  53. } catch (error) {
  54. if (this.#on_skip === null) {
  55. return ;
  56. }
  57. try {
  58. this.#on_skip(new import_process_fail(count, error));
  59. } catch (fail) {
  60. console.log(fail);
  61. }
  62. }
  63. });
  64. return this;
  65. }
  66. results() {
  67. return Array.from(this.#processed.values());
  68. }
  69. }