index.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. subCategories {
  104. _id name
  105. }
  106. }
  107. }`, {q: JSON.stringify([{_id}])}))
  108. //actionGoodById по аналогии
  109. const actionGoodById = (_id) =>
  110. actionPromise('goodById', gql(`query goodById($q: String) {
  111. GoodFindOne(query: $q) {
  112. _id name price description images {
  113. url
  114. }
  115. }
  116. }`, {q: JSON.stringify([{_id}])}))
  117. store.dispatch(actionRootCats())
  118. store.subscribe(() => {
  119. const {rootCats} = store.getState()
  120. if (rootCats?.payload) {
  121. aside.innerHTML = ''
  122. for (const {_id, name} of rootCats?.payload) {
  123. const link = document.createElement('a')
  124. link.href = `#/category/${_id}`
  125. link.innerText = name
  126. aside.append(link)
  127. }
  128. }
  129. })
  130. // location.hash - адресная строка после решетки
  131. window.onhashchange = () => {
  132. const [,route, _id] = location.hash.split('/')
  133. const routes = {
  134. category(){
  135. store.dispatch(actionCatById(_id))
  136. console.log('страница категорий')
  137. },
  138. good(){ //задиспатчить actionGoodById
  139. store.dispatch(actionGoodById(_id))
  140. console.log('страница товара')
  141. },
  142. }
  143. if (route in routes)
  144. routes[route]()
  145. }
  146. window.onhashchange()
  147. store.subscribe(() => {
  148. const {catById} = store.getState()
  149. const [,route, _id] = location.hash.split('/')
  150. if (catById?.payload && route === 'category'){
  151. const {name} = catById.payload;
  152. main.innerHTML = `<h1>${name}</h1>`
  153. if (catById.payload.subCategories) {
  154. for(const {_id, name} of catById.payload.subCategories) {
  155. const link = document.createElement('a');
  156. link.href = `#/category/${_id}`;
  157. link.innerText = name;
  158. main.append(link);
  159. }
  160. }
  161. if (catById.payload.goods) {
  162. for (const {_id, name, price, images} of catById.payload.goods){
  163. const card = document.createElement('div')
  164. card.innerHTML = `<h2>${name}</h2>
  165. <img src="${backURL}/${images[0].url}" />
  166. <strong>${price}</strong>
  167. <br>
  168. <a href="#/good/${_id}">Перейти на страницу товара</a>
  169. `
  170. main.append(card)
  171. }
  172. }
  173. }
  174. })
  175. store.subscribe(() => {
  176. const {goodById} = store.getState();
  177. const [,route, _id] = location.hash.split('/');
  178. if (goodById?.payload && route === 'good') {
  179. main.innerHTML = '';
  180. const {_id, name, images, price, description} = goodById.payload;
  181. const card = document.createElement('div');
  182. card.innerHTML = `<h2>${name}</h2>
  183. <img src="${backURL}/${images[0].url}" />
  184. <strong>${price}</strong>
  185. <h2>${description}</h2>
  186. `;
  187. main.append(card);
  188. }
  189. }
  190. //ТУТ ДОЛЖНА БЫТЬ ПРОВЕРКА НА НАЛИЧИЕ goodById в редакс
  191. //и проверка на то, что сейчас в адресной строке адрес ВИДА #/good/АЙДИ
  192. //в таком случае очищаем main и рисуем информацию про товар с подробностями
  193. )
  194. // store.dispatch(actionPromise('delay1000', delay(1000)))
  195. // store.dispatch(actionPromise('delay2000', delay(2000)))
  196. // store.dispatch(actionPromise('luke', fetch('https://swapi.dev/api/people/1/').then(res => res.json())))