Guest User

Untitled

a guest
Apr 24th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. // path: store/basket/basket.ts (module)
  2.  
  3. import { RootState } from "../../store"
  4. import inventory, { Product } from "../inventory/inventory"
  5.  
  6. export interface Item { productId: string, quantity: number }
  7. export interface DisplayItem { product: Product, quantity: number }
  8. export interface BasketState { items: Item[], isLoading: boolean }
  9.  
  10. const initialBasketState: BasketState = { items: [], isLoading: false }
  11. const b = getStoreBuilder<RootState>().module("basket", initialBasketState)
  12.  
  13. // getters
  14. const numberOfItemsGetter = b.read(state => state.items.length, "numberOfItems")
  15. const itemsGetter = b.read(state =>
  16. {
  17. const displayItems: DisplayItem[] = state.items.map(item =>
  18. {
  19. return {
  20. product: inventory.getProductById(item.productId),
  21. quantity: item.quantity
  22. }
  23. })
  24. return displayItems
  25. })
  26.  
  27. // mutations
  28. function appendItem(state: BasketState, payload: { productId: string, quantity: number })
  29. {
  30. state.items.push({
  31. productId: payload.productId,
  32. quantity: payload.quantity
  33. })
  34. }
  35.  
  36. function setIsLoading(state: BasketState, payload: { isLoading: boolean })
  37. {
  38. state.isLoading = payload.isLoading
  39. }
  40.  
  41. // action
  42. async function restoreSavedBasket(context: ActionContext<BasketState, RootState>)
  43. {
  44. const savedBasketId = localStorage["basketId"]
  45.  
  46. try
  47. {
  48. basket.commitSetIsLoading({ isLoading: true })
  49.  
  50. const { data: savedBasket } = await axios.get(`//chips-store.com/get-saved-basket/${savedBasketId}`, { responseType: "json" })
  51. const items: Item[] = savedBasket.items
  52. items.forEach(item => basket.commitAppendItem(item))
  53. }
  54. finally
  55. {
  56. basket.commitSetIsLoading({ isLoading: false })
  57. }
  58. }
  59.  
  60. // state
  61. const stateGetter = b.state()
  62.  
  63. // exported "basket" module interface
  64. const basket = {
  65. // state
  66. get state() { return stateGetter() },
  67.  
  68. // getters (wrapped as real getters)
  69. get items() { return itemsGetter() },
  70. get numberOfItems() { return numberOfItemsGetter() },
  71.  
  72. // mutations
  73. commitAppendItem: b.commit(appendItem),
  74. commitSetIsLoading: b.commit(setIsLoading),
  75.  
  76. // actions
  77. dispatchRestoreSavedBasket: b.dispatch(restoreSavedBasket)
  78. }
  79.  
  80. export default basket
Add Comment
Please, Sign In to add comment