index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 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)) // 1. {delay1000: {status: 'PENDING'}}
  38. try {
  39. let payload = await promise
  40. dispatch(actionResolved(name, payload))
  41. return payload
  42. }
  43. catch (error) {
  44. dispatch(actionRejected(name, error))
  45. }
  46. }
  47. const getGQL = url =>
  48. (query, variables = {}) =>
  49. fetch(url, {
  50. //метод
  51. method: 'POST',
  52. headers: {
  53. //заголовок content-type
  54. "Content-Type": "application/json",
  55. ...(localStorage.authToken ? { "Authorization": "Bearer " + localStorage.authToken } : {})
  56. },
  57. //body с ключами query и variables
  58. body: JSON.stringify({ query, variables })
  59. })
  60. .then(res => res.json())
  61. .then(data => {
  62. if (data.errors && !data.data)
  63. throw new Error(JSON.stringify(data.errors))
  64. return data.data[Object.keys(data.data)[0]]
  65. })
  66. const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  67. const gql = getGQL(`${backURL}/graphql`)
  68. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  69. /********************************MY STUFFF START****************************************************** */
  70. function jwtDecode(token){
  71. try {
  72. let decoded = token.split('.')
  73. decoded = decoded[1]
  74. decoded = atob(decoded)
  75. decoded = JSON.parse(decoded)
  76. return decoded
  77. } catch(e) {
  78. return;
  79. }
  80. }
  81. function authReducer(state, {type, token}){
  82. if (!state){
  83. if(!localStorage.authToken) {
  84. console.log('NO-TOKEN')
  85. return {}
  86. } else {
  87. type = 'AUTH_LOGIN'
  88. token = localStorage.authToken
  89. }
  90. }
  91. if (type === 'AUTH_LOGIN'){
  92. console.log('AUTH-LOGIN')
  93. let decoded = jwtDecode(token)
  94. if (decoded) {
  95. localStorage.authToken = token
  96. return {token, payload: decoded}
  97. }
  98. }
  99. if (type === 'AUTH_LOGOUT'){
  100. console.log('AUTH-LOGOUT')
  101. localStorage.removeItem('authToken')
  102. return {}
  103. }
  104. return state
  105. }
  106. function combineReducers(reducers){
  107. return (state={}, action) => {
  108. const newState = {}
  109. for (const [reducerName, reducer] of Object.entries(reducers)) {
  110. let newSubState = reducer(state[reducerName], action)
  111. if(newSubState !== state[reducerName]) {
  112. newState[reducerName] = newSubState
  113. }
  114. }
  115. if(Object.keys(newState).length !== 0) {
  116. return {...state, ...newState}
  117. }
  118. return state
  119. }
  120. }
  121. const combinedReducer = combineReducers({promise: promiseReducer, auth: authReducer})
  122. const store = createStore(combinedReducer)
  123. const actionAuthLogin = token => ({type: 'AUTH_LOGIN', token})
  124. const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'})
  125. //const store = createStore(authReducer)
  126. console.log(store.getState()) //стартовое состояние может быть с токеном
  127. store.subscribe(() => console.log(store.getState()))
  128. //ПЕРЕДЕЛАТЬ ОТОБРАЖЕНИЕ с поправкой на то, что теперь промисы не в корне state а в state.promise
  129. const actionLogin = (login, password) =>
  130. actionPromise('login', gql(`ЗАПРОС НА ЛОГИН`, {login ,password}))
  131. const actionFullLogin = (login, password) =>
  132. async dispatch => {
  133. let token = await dispatch(actionLogin(login, password))
  134. if (token){
  135. dispatch(actionAuthLogin(token))
  136. }
  137. }
  138. //const actionRegister //actionPromise
  139. //const actionFullRegister = (login, password) => //actionRegister + actionFullLogin
  140. //+ интерфейс к этому - форму логина, регистрации, может повесить это на #/login #/register
  141. //+ #/orders показывает ваши бывшие заказы:
  142. //сделать actionMyOrders
  143. //
  144. /********************************MY STUFFF END****************************************************** */
  145. const actionRootCats = () =>
  146. actionPromise('rootCats', gql(`query {
  147. CategoryFind(query: "[{\\"parent\\":null}]"){
  148. _id name
  149. }
  150. }`))
  151. const actionCatById = (_id) => //добавить подкатегории
  152. actionPromise('catById', gql(`query catById($q: String){
  153. CategoryFindOne(query: $q){
  154. _id
  155. name
  156. subCategories {
  157. _id name
  158. }
  159. goods {
  160. _id name price images {
  161. url
  162. }
  163. }
  164. }
  165. }`, { q: JSON.stringify([{ _id }]) }))
  166. store.dispatch(actionRootCats())
  167. const actionGoodById = (_id) =>
  168. actionPromise('goodById', gql(`
  169. query goodById ($good:String) {
  170. GoodFindOne(query: $good) {
  171. name
  172. description
  173. price
  174. categories {
  175. name
  176. }
  177. images {
  178. url
  179. }
  180. }
  181. }`, { good: JSON.stringify([{ _id }]) }))
  182. store.subscribe(() => {
  183. const { rootCats } = store.getState().promise
  184. if (rootCats?.payload) {
  185. aside.innerHTML = ''
  186. for (const { _id, name } of rootCats?.payload) {
  187. const link = document.createElement('a')
  188. link.href = `#/category/${_id}`
  189. link.innerText = name
  190. aside.append(link)
  191. }
  192. }
  193. })
  194. window.onhashchange = () => {
  195. const [, route, _id] = location.hash.split('/')
  196. const routes = {
  197. category() {
  198. store.dispatch(actionCatById(_id))
  199. },
  200. good() {
  201. store.dispatch(actionGoodById(_id))
  202. },
  203. }
  204. if (route in routes)
  205. routes[route]()
  206. }
  207. window.onhashchange()
  208. store.subscribe(() => {
  209. const { catById } = store.getState().promise
  210. const [, route, _id] = location.hash.split('/')
  211. if (catById?.payload && route === 'category') {
  212. const { name, subCategories } = catById.payload
  213. main.innerHTML = `<h1>${name}</h1>`
  214. if (subCategories) {
  215. console.log('here', subCategories)
  216. let subCats = document.createElement('div')
  217. for (let item of subCategories) {
  218. let link =document.createElement('a')
  219. link.innerHTML = `${item.name} &#9166`
  220. link.href = `#/category/${item._id}`
  221. link.style.margin = '10px'
  222. link.style.padding = '5px'
  223. link.style.backgroundColor = 'black'
  224. link.style.color = 'white'
  225. subCats.append(link)
  226. }
  227. main.append(subCats)
  228. }
  229. main.style.padding = "10px"
  230. if (catById.payload.goods) {
  231. for (const { _id, name, price, images } of catById.payload.goods) {
  232. const card = document.createElement('div')
  233. card.innerHTML = `
  234. <h2>${name}</h2>
  235. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  236. <br>
  237. <strong>Price: ${price}</strong>
  238. <br>
  239. <a href="#/good/${_id}">На страницу товара</a>
  240. `
  241. card.style.backgroundColor = "whitesmoke"
  242. card.style.border = "1px solid black"
  243. card.style.margin = "10px"
  244. card.style.padding = "10px"
  245. main.append(card)
  246. }
  247. }
  248. }
  249. })
  250. store.subscribe(() => {
  251. const { goodById } = store.getState().promise
  252. const [, route, _id] = location.hash.split('/')
  253. if (goodById?.payload && route === 'good') {
  254. const { name, categories, images, price, description } = goodById.payload
  255. main.innerHTML = `
  256. <div class="card">
  257. <button onclick="history.back()">&#8656 назад</button>
  258. <h1>${name}</h1>
  259. <h4>${categories[0].name}<h4>
  260. <br>
  261. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  262. <br>
  263. <strong>Price: ${price}</strong>
  264. <p>${description}</p>
  265. </div>
  266. `
  267. main.style.padding = "10px"
  268. }
  269. })
  270. window.onload = () => {
  271. location.href = "#/category/5dc49f4d5df9d670df48cc64"
  272. }