main.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. function createStore(reducer) {
  2. let state = reducer(undefined, {}) //стартовая инициализация состояния, запуск редьюсера со state === undefined
  3. let cbs = [] //массив подписчиков
  4. const getState = () => state //функция, возвращающая переменную из замыкания
  5. const subscribe = cb => (cbs.push(cb), //запоминаем подписчиков в массиве
  6. () => cbs = cbs.filter(c => c !== cb)) //возвращаем функцию unsubscribe, которая удаляет подписчика из списка
  7. const dispatch = action => {
  8. if (typeof action === 'function') { //если action - не объект, а функция
  9. return action(dispatch, getState) //запускаем эту функцию и даем ей dispatch и getState для работы
  10. }
  11. const newState = reducer(state, action) //пробуем запустить редьюсер
  12. if (newState !== state) { //проверяем, смог ли редьюсер обработать action
  13. state = newState //если смог, то обновляем state
  14. for (let cb of cbs) cb() //и запускаем подписчиков
  15. }
  16. }
  17. return {
  18. getState, //добавление функции getState в результирующий объект
  19. dispatch,
  20. subscribe //добавление subscribe в объект
  21. }
  22. }
  23. function promiseReducer(state = {}, { type, status, payload, error, name }) {
  24. if (type === 'PROMISE') {
  25. return {
  26. ...state,
  27. [name]: { status, payload, error }
  28. }
  29. }
  30. return state;
  31. }
  32. const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name })
  33. const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload })
  34. const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error })
  35. const actionPromise = (name, promise) =>
  36. async dispatch => {
  37. dispatch(actionPending(name))
  38. try {
  39. let data = await promise
  40. dispatch(actionResolved(name, data))
  41. return data
  42. }
  43. catch (error) {
  44. dispatch(actionRejected(name, error))
  45. }
  46. }
  47. const store = createStore(promiseReducer)
  48. store.subscribe(() => console.log(store.getState()))
  49. //const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  50. const getGQL = url =>
  51. async (query, variables = {}) => {
  52. let obj = await fetch(url, {
  53. method: 'POST',
  54. headers: {
  55. "Content-Type": "application/json"
  56. },
  57. body: JSON.stringify({ query, variables })
  58. })
  59. let a = await obj.json()
  60. if (!a.data && a.errors)
  61. throw new Error(JSON.stringify(a.errors))
  62. return a.data[Object.keys(a.data)[0]]
  63. }
  64. const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  65. const gql = getGQL(backURL + '/graphql');
  66. const actionRootCats = () =>
  67. actionPromise('rootCats', gql(`query {
  68. CategoryFind(query: "[{\\"parent\\":null}]"){
  69. _id name
  70. }
  71. }`))
  72. const actionCatById = (_id) => //добавить подкатегории
  73. actionPromise('catById', gql(`query catById($q: String){
  74. CategoryFindOne(query: $q){
  75. subCategories{name, _id}
  76. _id name goods {
  77. _id name price images {
  78. url
  79. }
  80. }
  81. }
  82. }`, { q: JSON.stringify([{ _id }]) }))
  83. //actionGoodById по аналогии
  84. const actionGoodById = (_id) => //добавить подкатегории
  85. actionPromise('goodById', gql(`query goodByID($q: String) {
  86. GoodFind(query: $q){
  87. name _id description price images{url}
  88. }
  89. }`, { q: JSON.stringify([{ _id }]) }))
  90. store.dispatch(actionRootCats())
  91. store.dispatch(actionGoodById())
  92. store.subscribe(() => {
  93. const { rootCats } = store.getState()
  94. if (rootCats?.payload) {
  95. aside.innerHTML = ''
  96. for (const { _id, name } of rootCats?.payload) {
  97. const link = document.createElement('a')
  98. link.href = `#/category/${_id}`
  99. link.innerText = name
  100. aside.append(link)
  101. }
  102. }
  103. })
  104. window.onhashchange = () => {
  105. const [, route, _id] = location.hash.split('/')
  106. const routes = {
  107. category() {
  108. store.dispatch(actionCatById(_id))
  109. },
  110. good() { //задиспатчить actionGoodById
  111. store.dispatch(actionGoodById(_id))
  112. },
  113. }
  114. if (route in routes)
  115. routes[route]()
  116. }
  117. window.onhashchange()
  118. store.subscribe(() => {
  119. const { catById } = store.getState()
  120. const [, route, _id] = location.hash.split('/')
  121. if (catById?.payload && route === 'category') {
  122. const { name, subCategories } = catById.payload
  123. main.innerHTML = `<h1>${name}</h1> `
  124. subCategories ? subCategories.map(s => {
  125. const link = document.createElement('a')
  126. link.href = `#/category/${s._id}`
  127. link.innerText = s.name
  128. main.append(link)
  129. }) : ''
  130. for (const { _id, name, price, images } of catById.payload.goods) {
  131. const card = document.createElement('div')
  132. card.innerHTML = `<h2>${name}</h2>
  133. <img src="${backURL}/${images[0].url}" />
  134. <strong>${price}</strong>`
  135. const link = document.createElement('a')
  136. link.href = `#/good/${_id}`
  137. link.innerText = name
  138. card.append(link)
  139. main.append(card)
  140. }
  141. }
  142. })
  143. store.subscribe(() => {
  144. const { goodById } = store.getState()
  145. const [, route, _id] = location.hash.split('/')
  146. if (goodById?.payload && route === 'good') {
  147. main.innerHTML = ''
  148. const { name, description, price, images } = goodById.payload[0]
  149. main.innerHTML = `
  150. <div div class="product" >
  151. <div class="product__img">
  152. <img src="${backURL}/${images[0].url}" />
  153. </div>
  154. <div class="product__inner">
  155. <h2 class="product_title">${name}</h2>
  156. <p class="product__price"> <strong>${price}</strong></p>
  157. <p class="product__description">
  158. <span>Обзор: ${description}</span>
  159. </p>
  160. </div>
  161. </div>`
  162. }
  163. })
  164. //store.dispatch(actionPromise('', delay(1000)))
  165. //store.dispatch(actionPromise('delay2000', delay(2000)))
  166. //store.dispatch(actionPromise('luke', fetch('https://swapi.dev/api/people/1/').then(res => res.json())))