summaryrefslogtreecommitdiff
path: root/iridescence/src/store/index.js
blob: fc77f7959824dacefd3a7dd3869263a21c9b7f25 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import Vue from "vue";
import Vuex from "vuex";
import Dichroism from "@/api/dichroism.js";

Vue.use(Vuex);

let dichroism = new Dichroism();

export default new Vuex.Store({
  state: {
    searchTerm: "",
    products: [],
    busy: false,
    progress: 100
  },
  getters: {
    busy(state) {
      return state.busy;
    },
    progress(state) {
      return state.progress;
    },
    products(state) {
      return state.products.filter(item => {
        return JSON.stringify(item)
          .toLowerCase()
          .includes(state.searchTerm.toLowerCase());
      });
    }
  },
  mutations: {
    searchTerm(state, term) {
      if (term) {
        state.searchTerm = term;
      }
    },
    setProducts(state, products) {
      if (products) {
        state.products = products;
      }
    },
    replaceProduct(state, product) {
      let index = state.products.findIndex(p => p.id == product.id);

      if (product && index >= 0) {
        state.products[index] = product;
      }
    },
    addProduct(state, product) {
      if (product) {
        state.products.push(product);
      }
    }
  },
  actions: {
    async refreshProducts(context) {
      const products = await dichroism.getProducts();
      context.commit("setProducts", products);
    },
    async updateProduct(context, product) {
      const updatedProduct = await dichroism.updateProduct(product);
      context.dispatch("replaceProduct", updatedProduct);
    },
    async createProduct(context, product) {
      const newProduct = await dichroism.createProduct(product);
      context.dispatch("addProduct", newProduct);
    }
  },
  modules: {}
});