index.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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, name, status, payload, error }) {
  24. if (type === 'PROMISE') {
  25. return {
  26. ...state,
  27. [name]: { status, payload, error }
  28. }
  29. }
  30. return state
  31. }
  32. const store = createStore(promiseReducer)
  33. store.subscribe(() => console.log('state of store:', store.getState()))
  34. const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name })
  35. const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload })
  36. const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error })
  37. const actionPromise = (name, promise) =>
  38. async dispatch => {
  39. dispatch(actionPending(name)) // 1. {delay1000: {status: 'PENDING'}}
  40. try {
  41. let payload = await promise
  42. dispatch(actionResolved(name, payload))
  43. return payload
  44. }
  45. catch (error) {
  46. dispatch(actionRejected(name, error))
  47. }
  48. }
  49. const getGQL = url =>
  50. (query, variables = {}) =>
  51. fetch(url, {
  52. //метод
  53. method: 'POST',
  54. headers: {
  55. //заголовок content-type
  56. "Content-Type": "application/json",
  57. ...(localStorage.authToken ? { "Authorization": "Bearer " + localStorage.authToken } : {})
  58. },
  59. //body с ключами query и variables
  60. body: JSON.stringify({ query, variables })
  61. })
  62. .then(res => res.json())
  63. .then(data => {
  64. if (data.errors && !data.data)
  65. throw new Error(JSON.stringify(data.errors))
  66. return data.data[Object.keys(data.data)[0]]
  67. })
  68. const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  69. const gql = getGQL(`${backURL}/graphql`)
  70. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  71. const actionRootCats = () =>
  72. actionPromise('rootCats', gql(`query {
  73. CategoryFind(query: "[{\\"parent\\":null}]"){
  74. _id name
  75. }
  76. }`))
  77. const actionCatById = (_id) => //добавить подкатегории
  78. actionPromise('catById', gql(`query catById($q: String){
  79. CategoryFindOne(query: $q){
  80. _id
  81. name
  82. subCategories {
  83. _id name
  84. }
  85. goods {
  86. _id name price images {
  87. url
  88. }
  89. }
  90. }
  91. }`, { q: JSON.stringify([{ _id }]) }))
  92. store.dispatch(actionRootCats())
  93. const actionGoodById = (_id) =>
  94. actionPromise('goodById', gql(`
  95. query goodById ($good:String) {
  96. GoodFindOne(query: $good) {
  97. name
  98. description
  99. price
  100. categories {
  101. name
  102. }
  103. images {
  104. url
  105. }
  106. }
  107. }`, { good: JSON.stringify([{ _id }]) }))
  108. store.subscribe(() => {
  109. //console.log(location)
  110. const { rootCats } = store.getState()
  111. if (rootCats?.payload) {
  112. aside.innerHTML = ''
  113. for (const { _id, name } of rootCats?.payload) {
  114. const link = document.createElement('a')
  115. link.href = `#/category/${_id}`
  116. link.innerText = name
  117. aside.append(link)
  118. }
  119. }
  120. })
  121. window.onhashchange = () => {
  122. const [, route, _id] = location.hash.split('/')
  123. const routes = {
  124. category() {
  125. store.dispatch(actionCatById(_id))
  126. },
  127. good() { //задиспатчить actionGoodById
  128. store.dispatch(actionGoodById(_id))
  129. },
  130. }
  131. if (route in routes)
  132. routes[route]()
  133. }
  134. window.onhashchange()
  135. store.subscribe(() => {
  136. //console.log(location)
  137. //console.log('drawing cat list')
  138. const { catById } = store.getState()
  139. const [, route, _id] = location.hash.split('/')
  140. if (catById?.payload && route === 'category') {
  141. const { name, subCategories } = catById.payload
  142. main.innerHTML = `<h1>${name}</h1>`
  143. if (subCategories) {
  144. console.log('here', subCategories)
  145. let subCats = document.createElement('div')
  146. for (let item of subCategories) {
  147. let link =document.createElement('a')
  148. link.innerHTML = `${item.name} &#9166`
  149. link.href = `#/category/${item._id}`
  150. link.style.margin = '10px'
  151. link.style.padding = '5px'
  152. link.style.backgroundColor = 'black'
  153. link.style.color = 'white'
  154. subCats.append(link)
  155. }
  156. main.append(subCats)
  157. }
  158. main.style.padding = "10px"
  159. if (catById.payload.goods) {
  160. for (const { _id, name, price, images } of catById.payload.goods) {
  161. const card = document.createElement('div')
  162. card.innerHTML = `
  163. <h2>${name}</h2>
  164. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  165. <br>
  166. <strong>Price: ${price}</strong>
  167. <br>
  168. <a href="#/good/${_id}">На страницу товара</a>
  169. `
  170. card.style.backgroundColor = "whitesmoke"
  171. card.style.border = "1px solid black"
  172. card.style.margin = "10px"
  173. card.style.padding = "10px"
  174. main.append(card)
  175. }
  176. }
  177. }
  178. })
  179. store.subscribe(() => {
  180. //console.log('drawing page of good')
  181. const { goodById } = store.getState()
  182. const [, route, _id] = location.hash.split('/')
  183. if (goodById?.payload && route === 'good') {
  184. const { name, categories, images, price, description } = goodById.payload
  185. main.innerHTML = `
  186. <div class="card">
  187. <button onclick="history.back()">&#8656 назад</button>
  188. <h1>${name}</h1>
  189. <h4>${categories[0].name}<h4>
  190. <br>
  191. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  192. <br>
  193. <strong>Price: ${price}</strong>
  194. <p>${description}</p>
  195. </div>
  196. `
  197. main.style.padding = "10px"
  198. }
  199. })
  200. window.onload = () => {
  201. location.href = location.href + "#/category/5dc49f4d5df9d670df48cc64"
  202. }