cart.js 2.1 KB

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