cart.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import shop from '../../api/shop'
  2. import nested from './nested'
  3. // initial state
  4. // shape: [{ id, quantity }]
  5. const state = () => ({
  6. items: [],
  7. checkoutStatus: null
  8. })
  9. // getters
  10. const getters = {
  11. cartProducts: (state, getters, rootState) => {
  12. return state.items.map(({ id, quantity }) => {
  13. const product = rootState.products.all.find(product => product.id === id)
  14. return {
  15. title: product.title,
  16. price: product.price,
  17. quantity
  18. }
  19. })
  20. },
  21. cartTotalPrice: (state, getters) => {
  22. return getters.cartProducts.reduce((total, product) => {
  23. return total + product.price * product.quantity
  24. }, 0)
  25. }
  26. }
  27. // actions
  28. const actions = {
  29. async checkout ({ commit, state }, products) {
  30. const savedCartItems = [...state.items]
  31. commit('setCheckoutStatus', null)
  32. // empty cart
  33. commit('setCartItems', { items: [] })
  34. try {
  35. await shop.buyProducts(products)
  36. commit('setCheckoutStatus', 'successful')
  37. } catch (e) {
  38. console.error(e)
  39. commit('setCheckoutStatus', 'failed')
  40. // rollback to the cart saved before sending the request
  41. commit('setCartItems', { items: savedCartItems })
  42. }
  43. },
  44. addProductToCart ({ state, commit }, product) {
  45. commit('setCheckoutStatus', null)
  46. if (product.inventory > 0) {
  47. const cartItem = state.items.find(item => item.id === product.id)
  48. if (!cartItem) {
  49. commit('pushProductToCart', { id: product.id })
  50. } else {
  51. commit('incrementItemQuantity', cartItem)
  52. }
  53. // remove 1 item from stock
  54. commit('products/decrementProductInventory', { id: product.id }, { root: true })
  55. }
  56. }
  57. }
  58. // mutations
  59. const mutations = {
  60. pushProductToCart (state, { id }) {
  61. state.items.push({
  62. id,
  63. quantity: 1
  64. })
  65. },
  66. incrementItemQuantity (state, { id }) {
  67. const cartItem = state.items.find(item => item.id === id)
  68. cartItem.quantity++
  69. },
  70. setCartItems (state, { items }) {
  71. state.items = items
  72. },
  73. setCheckoutStatus (state, status) {
  74. state.checkoutStatus = status
  75. }
  76. }
  77. export default {
  78. namespaced: true,
  79. state,
  80. getters,
  81. actions,
  82. mutations,
  83. modules: {
  84. nested
  85. }
  86. }