cart.js 911 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import {
  2. ADD_TO_CART,
  3. CHECKOUT_REQUEST,
  4. CHECKOUT_SUCCESS,
  5. CHECKOUT_FAILURE
  6. } from '../mutation-types'
  7. // initial state
  8. // shape: [{ id, quantity }]
  9. export const cartInitialState = {
  10. added: [],
  11. lastCheckout: null
  12. }
  13. // mutations
  14. export const cartMutations = {
  15. [ADD_TO_CART] ({ cart }, productId) {
  16. cart.lastCheckout = null
  17. const record = cart.added.find(p => p.id === productId)
  18. if (!record) {
  19. cart.added.push({
  20. id: productId,
  21. quantity: 1
  22. })
  23. } else {
  24. record.quantity++
  25. }
  26. },
  27. [CHECKOUT_REQUEST] ({ cart }) {
  28. // clear cart
  29. cart.added = []
  30. cart.lastCheckout = null
  31. },
  32. [CHECKOUT_SUCCESS] ({ cart }) {
  33. cart.lastCheckout = 'successful'
  34. },
  35. [CHECKOUT_FAILURE] ({ cart }, savedCartItems) {
  36. // rollback to the cart saved before sending the request
  37. cart.added = savedCartItems
  38. cart.lastCheckout = 'failed'
  39. }
  40. }