index.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 (!state) {
  25. return {}
  26. //{ login: {status, payload, error},
  27. // catById: {status, payload, error}
  28. //}
  29. }
  30. if (type === 'PROMISE') {
  31. return {
  32. ...state,
  33. [name]: {
  34. status: status,
  35. payload : payload,
  36. error: error,
  37. }
  38. }
  39. }
  40. return state
  41. }
  42. const actionPending = (name) => ({type: 'PROMISE', status: 'PENDING', name})
  43. const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload})
  44. const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error})
  45. const store = createStore(promiseReducer)
  46. store.subscribe(() => console.log(store.getState()))
  47. // const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms))
  48. // store.dispatch(actionPending('delay1000'))
  49. // delay(1000).then(data => store.dispatch(actionResolved('delay1000', data)),
  50. // error => store.dispatch(actionRejected('delay1000', error)))
  51. // store.dispatch(actionPending('delay2000'))
  52. // delay(2000).then(data => store.dispatch(actionResolved('delay2000', data)),
  53. // error => store.dispatch(actionRejected('delay2000', error)))
  54. const actionPromise = (name, promise) =>
  55. async dispatch => {
  56. dispatch(actionPending(name))
  57. try {
  58. let data = await promise
  59. dispatch(actionResolved(name, data))
  60. return data
  61. }
  62. catch(error){
  63. dispatch(actionRejected(name, error))
  64. }
  65. }
  66. const getGQL = url =>
  67. async (query, variables={}) => {
  68. // try {
  69. let obj = await fetch(url, {
  70. method: 'POST',
  71. headers: {
  72. "Content-Type": "application/json"
  73. },
  74. body: JSON.stringify({ query, variables })
  75. })
  76. let a = await obj.json()
  77. if (!a.data && a.errors) {
  78. throw new Error(JSON.stringify(a.errors))
  79. } else {
  80. return a.data[Object.keys(a.data)[0]]
  81. }
  82. // }
  83. // catch (error) {
  84. // console.log('Что-то не так, Бро ' + error);
  85. // }
  86. }
  87. const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua/'
  88. const gql = getGQL(backURL + 'graphql');
  89. const actionRootCats = () =>
  90. actionPromise('rootCats', gql(`query {
  91. CategoryFind(query: "[{\\"parent\\":null}]"){
  92. _id name
  93. }
  94. }`))
  95. const actionCatById = (_id) =>
  96. actionPromise('catById', gql(`query catById($q: String){
  97. CategoryFindOne(query: $q){
  98. _id name goods {
  99. _id name price images {
  100. url
  101. }
  102. }
  103. }
  104. }`, {q: JSON.stringify([{_id}])}))
  105. //actionGoodById по аналогии
  106. store.dispatch(actionRootCats())
  107. store.subscribe(() => {
  108. const {rootCats} = store.getState()
  109. if (rootCats?.payload) {
  110. aside.innerHTML = ''
  111. for (const {_id, name} of rootCats?.payload) {
  112. const link = document.createElement('a')
  113. link.href = `#/category/${_id}`
  114. link.innerText = name
  115. aside.append(link)
  116. }
  117. }
  118. })
  119. // location.hash - адресная строка после решетки
  120. window.onhashchange = () => {
  121. const [, route, _id] = location.hash.split('/')
  122. const routes = {
  123. category() {
  124. store.dispatch(actionCatById(_id))
  125. },
  126. good() {
  127. //задиспатчить actionGoodById
  128. },
  129. }
  130. if (route in routes) {
  131. routes[route]()
  132. }
  133. }
  134. // запускает обработчик при загрузке страницы
  135. window.onhashchange()
  136. store.subscribe(() => {
  137. const {catById} = store.getState()
  138. const [,route, _id] = location.hash.split('/')
  139. if (catById?.payload && route === 'category'){
  140. const {name} = catById.payload
  141. main.innerHTML = `<h1>${name}</h1> ТУТ ДОЛЖНЫ БЫТЬ ПОДКАТЕГОРИИ`
  142. for (const {_id, name, price, images} of catById.payload.goods){
  143. const card = document.createElement('div')
  144. card.innerHTML = `<h2>${name}</h2>
  145. <img src="${backURL}/${images[0].url}" />
  146. <strong>${price}</strong>
  147. ТУТ ДОЛЖНА БЫТЬ ССЫЛКА НА СТРАНИЦУ ТОВАРА
  148. ВИДА #/good/АЙДИ
  149. `
  150. main.append(card)
  151. }
  152. }
  153. })
  154. store.subscribe(() => {
  155. //ТУТ ДОЛЖНА БЫТЬ ПРОВЕРКА НА НАЛИЧИЕ goodById в редакс
  156. //и проверка на то, что сейчас в адресной строке адрес ВИДА #/good/АЙДИ
  157. //в таком случае очищаем main и рисуем информацию про товар с подробностями
  158. })
  159. // store.dispatch(actionPromise('delay1000', delay(1000)))
  160. // store.dispatch(actionPromise('delay2000', delay(2000)))
  161. // store.dispatch(actionPromise('luke', fetch('https://swapi.dev/api/people/1/').then(res => res.json())))