index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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=undefined, password=undefined) =>
  130. actionPromise('login', gql(`
  131. query log($login:String, $password:String) {
  132. login(login: $login, password: $password)
  133. }`, {login ,password}))
  134. const actionFullLogin = (login, password) =>
  135. async dispatch => {
  136. let token = await dispatch(actionLogin(login, password))
  137. if (token){
  138. dispatch(actionAuthLogin(token))
  139. }
  140. }
  141. //const actionRegister //actionPromise
  142. //const actionFullRegister = (login, password) => //actionRegister + actionFullLogin
  143. //+ интерфейс к этому - форму логина, регистрации, может повесить это на #/login #/register
  144. //+ #/orders показывает ваши бывшие заказы:
  145. //сделать actionMyOrders
  146. //
  147. let logBtn = document.getElementById('logBtn')
  148. logBtn.onclick = () => {
  149. location.href = "#/login"
  150. store.dispatch(actionLogin())
  151. }
  152. /********************************MY STUFFF END****************************************************** */
  153. const actionRootCats = () =>
  154. actionPromise('rootCats', gql(`query {
  155. CategoryFind(query: "[{\\"parent\\":null}]"){
  156. _id name
  157. }
  158. }`))
  159. const actionCatById = (_id) => //добавить подкатегории
  160. actionPromise('catById', gql(`query catById($q: String){
  161. CategoryFindOne(query: $q){
  162. _id
  163. name
  164. subCategories {
  165. _id name
  166. }
  167. goods {
  168. _id name price images {
  169. url
  170. }
  171. }
  172. }
  173. }`, { q: JSON.stringify([{ _id }]) }))
  174. store.dispatch(actionRootCats())
  175. const actionGoodById = (_id) =>
  176. actionPromise('goodById', gql(`
  177. query goodById ($good:String) {
  178. GoodFindOne(query: $good) {
  179. name
  180. description
  181. price
  182. categories {
  183. name
  184. }
  185. images {
  186. url
  187. }
  188. }
  189. }`, { good: JSON.stringify([{ _id }]) }))
  190. store.subscribe(() => {
  191. const { rootCats } = store.getState().promise
  192. if (rootCats?.payload) {
  193. aside.innerHTML = ''
  194. for (const { _id, name } of rootCats?.payload) {
  195. const link = document.createElement('a')
  196. link.href = `#/category/${_id}`
  197. link.innerText = name
  198. aside.append(link)
  199. }
  200. }
  201. })
  202. window.onhashchange = () => {
  203. const [, route, _id] = location.hash.split('/')
  204. const routes = {
  205. category() {
  206. store.dispatch(actionCatById(_id))
  207. },
  208. good() {
  209. store.dispatch(actionGoodById(_id))
  210. },
  211. login() {
  212. }
  213. }
  214. if (route in routes)
  215. routes[route]()
  216. }
  217. window.onhashchange()
  218. store.subscribe(() => {
  219. const { catById } = store.getState().promise
  220. const [, route, _id] = location.hash.split('/')
  221. if (catById?.payload && route === 'category') {
  222. const { name, subCategories } = catById.payload
  223. main.innerHTML = `<h1>${name}</h1>`
  224. if (subCategories) {
  225. console.log('here', subCategories)
  226. let subCats = document.createElement('div')
  227. for (let item of subCategories) {
  228. let link =document.createElement('a')
  229. link.innerHTML = `${item.name} &#9166`
  230. link.href = `#/category/${item._id}`
  231. link.style.margin = '10px'
  232. link.style.padding = '5px'
  233. link.style.backgroundColor = 'black'
  234. link.style.color = 'white'
  235. subCats.append(link)
  236. }
  237. main.append(subCats)
  238. }
  239. main.style.padding = "10px"
  240. if (catById.payload.goods) {
  241. for (const { _id, name, price, images } of catById.payload.goods) {
  242. const card = document.createElement('div')
  243. card.innerHTML = `
  244. <h2>${name}</h2>
  245. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  246. <br>
  247. <strong>Price: ${price}</strong>
  248. <br>
  249. <a href="#/good/${_id}">На страницу товара</a>
  250. `
  251. card.style.backgroundColor = "whitesmoke"
  252. card.style.border = "1px solid black"
  253. card.style.margin = "10px"
  254. card.style.padding = "10px"
  255. main.append(card)
  256. }
  257. }
  258. }
  259. })
  260. store.subscribe(() => {
  261. const { goodById } = store.getState().promise
  262. const [, route, _id] = location.hash.split('/')
  263. if (goodById?.payload && route === 'good') {
  264. const { name, categories, images, price, description } = goodById.payload
  265. main.innerHTML = `
  266. <div class="card">
  267. <button onclick="history.back()">&#8656 назад</button>
  268. <h1>${name}</h1>
  269. <h4>${categories[0].name}<h4>
  270. <br>
  271. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  272. <br>
  273. <strong>Price: ${price}</strong>
  274. <p>${description}</p>
  275. </div>
  276. `
  277. main.style.padding = "10px"
  278. }
  279. })
  280. store.subscribe(()=> {
  281. const { login } = store.getState().promise
  282. const [, route, _id] = location.hash.split('/')
  283. let passInp, logInp
  284. if(!login?.payload && route === 'login') {
  285. console.log('hire');
  286. aside.innerHTML = ''
  287. main.innerHTML = `
  288. <div style="border: 1px solid black; padding: 10px">
  289. <button id="returnBtnLogin">&#8656 назад</button>
  290. <input id="logInp" style="display:block; margin:10px" type="text" placeholder="login"/>
  291. <input id="passInp" style="display:block; margin:10px" type="text" placeholder="password"/>
  292. <button style="display:block; margin:0 auto">LOGIN</button>
  293. </div>
  294. `
  295. let returnBtn = document.getElementById('returnBtnLogin')
  296. logInp = document.getElementById('logInp')
  297. passInp = document.getElementById('passInp')
  298. returnBtn.onclick = () => {
  299. logBtn.disabled = false
  300. history.back()
  301. }
  302. logBtn.disabled = true
  303. }
  304. })
  305. window.onload = () => {
  306. location.href = "#/category/5dc49f4d5df9d670df48cc64"
  307. }