cart.js 2.2 KB

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