aboutsummaryrefslogtreecommitdiff
path: root/client/src/store/index.js
blob: 086c5449078279defadab81c7ed7867cf5ed115d (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import {createStore} from 'vuex'
import axios from 'axios';

export default createStore({
  state: {
    products: [],
    currentProduct: {},
    cart: []
  },
  getters: {
    getProducts(state) {
      return state.products;
    },
    getCart(state) {
      return state.cart.sort((x, y) => x.name > y.name);
    },
    getCartSize(state) {
      let sum = 0;
      state.cart.forEach(x => sum += x.quantity);
      return sum;
    },
    getCartPrice(state) {
      let sum = 0;
      state.cart.forEach(x => sum += x.price * x.quantity);
      return sum;
    },
    getCurrentProduct(state) {
      return state.currentProduct;
    },
    getCurrentProductImgUrl(state) {
      return `${process.env.VUE_APP_ROOT_API}/${state.currentProduct.imagePath}`;
    },
    getCurrentProductQuantity(state) {
      let amount = 0
      state.cart.forEach(x => {
        if (x.id == state.currentProduct._id)
          amount = x.quantity;
      });
      return amount;
    }
  },
  mutations: {
    setProducts(state, products) {
      state.products = products;
    },
    setCurrentProduct(state, product) {
      state.currentProduct = product;
    },
    addToCart(state) {
      let foundProduct = state.cart.find(x => x.id == state.currentProduct._id);
      if (foundProduct)
        foundProduct.quantity++;
      else
        state.cart.push({
          id: state.currentProduct._id,
          name: state.currentProduct.name,
          price: state.currentProduct.price,
          quantity: 1
        });
    },
    removeFromCart(state) {
      let foundProduct = state.cart.find(x => x.id == state.currentProduct._id);
      if (foundProduct) {
        foundProduct.quantity--;
        if (foundProduct.quantity == 0)
          state.cart = state.cart.filter(x => x.id != foundProduct.id);
      }
    }
  },
  actions: {
    async pullProducts(context) {
      await axios.get(`${process.env.VUE_APP_ROOT_API}/products`)
        .then(response => context.commit('setProducts', response.data))
        .catch(error => console.error(error));
    },
    async pullProduct(context, productId) {
      await axios.get(`${process.env.VUE_APP_ROOT_API}/products/${productId}`)
        .then(response => context.commit('setCurrentProduct', response.data))
        .catch(error => console.error(error));
    }
  },
  modules: {
  }
})