cart.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import shop from '../../api/shop'
  2. import * as types from '../mutation-types'
  3. // initial state
  4. // shape: [{ id, quantity }]
  5. const state = {
  6. added: [],
  7. checkoutStatus: null
  8. }
  9. // getters
  10. const getters = {
  11. checkoutStatus: state => state.checkoutStatus
  12. }
  13. // actions
  14. const actions = {
  15. checkout ({ commit, state }, products) {
  16. const savedCartItems = [...state.added]
  17. commit(types.CHECKOUT_REQUEST)
  18. shop.buyProducts(
  19. products,
  20. () => commit(types.CHECKOUT_SUCCESS),
  21. () => commit(types.CHECKOUT_FAILURE, { savedCartItems })
  22. )
  23. }
  24. }
  25. // mutations
  26. const mutations = {
  27. [types.ADD_TO_CART] (state, { id }) {
  28. state.lastCheckout = null
  29. const record = state.added.find(p => p.id === id)
  30. if (!record) {
  31. state.added.push({
  32. id,
  33. quantity: 1
  34. })
  35. } else {
  36. record.quantity++
  37. }
  38. },
  39. [types.CHECKOUT_REQUEST] (state) {
  40. // clear cart
  41. state.added = []
  42. state.checkoutStatus = null
  43. },
  44. [types.CHECKOUT_SUCCESS] (state) {
  45. state.checkoutStatus = 'successful'
  46. },
  47. [types.CHECKOUT_FAILURE] (state, { savedCartItems }) {
  48. // rollback to the cart saved before sending the request
  49. state.added = savedCartItems
  50. state.checkoutStatus = 'failed'
  51. }
  52. }
  53. export default {
  54. state,
  55. getters,
  56. actions,
  57. mutations
  58. }