index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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, cart: cartReducer })
  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. /********************************MY STUFFF CART START****************************************************** */
  154. function cartReducer(state = {}, { type, good={}, count = 1 }) {
  155. //{
  156. // _id1: {good, count}
  157. // _id2: {good, count}
  158. //}
  159. let { _id } = good
  160. const types = {
  161. CART_ADD() { //как CHANGE, только если ключ раньше был, то достать из count и добавить
  162. //к count из action. Если не было, достать 0 и добавить к count из action
  163. return {
  164. ...state,
  165. [_id]: { good, count: (state[_id]?.count || 0) + count }
  166. }
  167. },
  168. CART_REMOVE() { //смочь скопировать объект и выкинуть ключ. как вариант через
  169. //деструктуризацию
  170. let { _id, ...newState } = state
  171. return newState
  172. },
  173. CART_CHANGE() {
  174. return {
  175. ...state, //по аналогии с promiseReducer дописать
  176. [_id]: { good, count }
  177. }
  178. },
  179. CART_CLEAR() {
  180. return {}
  181. },
  182. }
  183. if (type in types)
  184. return types[type]()
  185. return state
  186. }
  187. //понаписывать action
  188. //прикрутить к товару кнопку которая делает store.dispatch(actionCartAdd(good))
  189. const actionCartAdd = (good, count = 1) => ({ type: 'CART_ADD', good, count })
  190. const actionCartDel = (good, count = 1) => ({ type: 'CART_REMOVE', good, count})
  191. /********************************MY STUFFF CART END****************************************************** */
  192. const actionRootCats = () =>
  193. actionPromise('rootCats', gql(`query {
  194. CategoryFind(query: "[{\\"parent\\":null}]"){
  195. _id name
  196. }
  197. }`))
  198. const actionCatById = (_id) => //добавить подкатегории
  199. actionPromise('catById', gql(`query catById($q: String){
  200. CategoryFindOne(query: $q){
  201. _id
  202. name
  203. subCategories {
  204. _id name
  205. }
  206. goods {
  207. _id name price images {
  208. url
  209. }
  210. }
  211. }
  212. }`, { q: JSON.stringify([{ _id }]) }))
  213. store.dispatch(actionRootCats())
  214. const actionGoodById = (_id) =>
  215. actionPromise('goodById', gql(`
  216. query goodById ($good:String) {
  217. GoodFindOne(query: $good) {
  218. name
  219. description
  220. price
  221. categories {
  222. name
  223. }
  224. images {
  225. url
  226. }
  227. }
  228. }`, { good: JSON.stringify([{ _id }]) }))
  229. store.subscribe(() => {
  230. const { rootCats } = store.getState().promise
  231. if (rootCats?.payload) {
  232. aside.innerHTML = ''
  233. for (const { _id, name } of rootCats?.payload) {
  234. const link = document.createElement('a')
  235. link.href = `#/category/${_id}`
  236. link.innerText = name
  237. aside.append(link)
  238. }
  239. }
  240. })
  241. window.onhashchange = () => {
  242. const [, route, _id] = location.hash.split('/')
  243. const routes = {
  244. category() {
  245. store.dispatch(actionCatById(_id))
  246. },
  247. good() {
  248. store.dispatch(actionGoodById(_id))
  249. },
  250. login() {
  251. },
  252. cart() {
  253. const {cart} = store.getState()
  254. aside.innerHTML = ''
  255. main.innerHTML = `
  256. <button onclick="history.back()" style="font-size: smaller;">&#8656 назад</button>
  257. <h2>Корзина</h2>
  258. <h4>Общая цена заказов:<span id="fullPrice"></span></h4>
  259. <button id="clearCartBtn" style="background-color: firebrick; color: white; font-size: smaller;">Очистить корзину</button>
  260. <br>
  261. `
  262. let clearCartBtn = document.getElementById('clearCartBtn')
  263. clearCartBtn.onclick = () => {
  264. //clear cart action
  265. }
  266. let fullPrice = 0
  267. for(let item in cart) {
  268. let orderPrice = cart[item].good.price * cart[item].count
  269. let card = document.createElement('div')
  270. fullPrice += orderPrice
  271. let delOrderBtn = document.createElement('button')
  272. delOrderBtn.style.backgroundColor = "firebrick"
  273. delOrderBtn.style.color = "white"
  274. delOrderBtn.style.fontSize = "smaller"
  275. delOrderBtn.style.float = "right"
  276. delOrderBtn.innerText = "Удалить заказ [x]"
  277. card.append(delOrderBtn)
  278. delOrderBtn.onclick = () => {
  279. console.log('nuaaaaaa', cart[item].good)
  280. store.dispatch(actionCartDel(cart[item].good))
  281. }
  282. card.insertAdjacentHTML('beforeend', `
  283. <br>
  284. <h2>${cart[item].good.name}</h2>
  285. <div style="border:5px solid mediumvioletred; background-color: black; color: white; padding: 0px 5px;">
  286. <h4>Кол-во: ${cart[item].count}</h4>
  287. <h4>Стоимость заказа: ${orderPrice}</h4>
  288. </div>
  289. <br>
  290. <img style="border: 1px dashed grey;" src="${backURL}/${cart[item].good.images[0].url}" />
  291. <br>
  292. <strong>Цена за ед. товара: ${cart[item].good.price}</strong>
  293. <br>
  294. <a href="#/good/${cart[item].good._id}">На страницу товара</a>
  295. <br>
  296. `)
  297. card.style.backgroundColor = "whitesmoke"
  298. card.style.border = "1px solid black"
  299. card.style.margin = "10px"
  300. card.style.padding = "10px"
  301. main.append(card)
  302. }
  303. console.log('full prise', fullPrice)
  304. let fullPriceSpan = document.getElementById('fullPrice')
  305. fullPriceSpan.innerText = `${fullPrice}`
  306. }
  307. }
  308. if (route in routes)
  309. routes[route]()
  310. }
  311. window.onhashchange()
  312. store.subscribe(() => {
  313. const { catById } = store.getState().promise
  314. const [, route, _id] = location.hash.split('/')
  315. if (catById?.payload && route === 'category') {
  316. const { name, subCategories } = catById.payload
  317. main.innerHTML = `<h1>${name}</h1>`
  318. if (subCategories) {
  319. console.log('here', subCategories)
  320. let subCats = document.createElement('div')
  321. for (let item of subCategories) {
  322. let link = document.createElement('a')
  323. link.innerHTML = `${item.name} &#9166`
  324. link.href = `#/category/${item._id}`
  325. link.style.margin = '10px'
  326. link.style.padding = '5px'
  327. link.style.backgroundColor = 'black'
  328. link.style.color = 'white'
  329. subCats.append(link)
  330. }
  331. main.append(subCats)
  332. }
  333. main.style.padding = "10px"
  334. if (catById.payload.goods) {
  335. for (const good of catById.payload.goods) {
  336. const card = document.createElement('div')
  337. card.innerHTML = `
  338. <h2>${good.name}</h2>
  339. <img style="border: 1px dashed grey;" src="${backURL}/${good.images[0].url}" />
  340. <br>
  341. <strong>Price: ${good.price}</strong>
  342. <br>
  343. <a href="#/good/${good._id}">На страницу товара</a>
  344. <br>
  345. `
  346. card.style.backgroundColor = "whitesmoke"
  347. card.style.border = "1px solid black"
  348. card.style.margin = "10px"
  349. card.style.padding = "10px"
  350. main.append(card)
  351. let cartButton = document.createElement('button')
  352. cartButton.innerText = 'Добавить в корзину'
  353. cartButton.style.fontSize = 'smaller'
  354. card.append(cartButton)
  355. cartButton.onclick = () => {
  356. console.log('nuaaaaaa', good)
  357. store.dispatch(actionCartAdd(good))
  358. }
  359. }
  360. }
  361. }
  362. })
  363. store.subscribe(() => {
  364. const { goodById } = store.getState().promise
  365. const [, route, _id] = location.hash.split('/')
  366. if (goodById?.payload && route === 'good') {
  367. const { name, categories, images, price, description } = goodById.payload
  368. main.innerHTML = `
  369. <div class="card">
  370. <button onclick="history.back()" style="font-size: smaller;">&#8656 назад</button>
  371. <h1>${name}</h1>
  372. <h4>${categories[0].name}<h4>
  373. <br>
  374. <img style="border: 1px dashed grey;" src="${backURL}/${images[0].url}" />
  375. <br>
  376. <strong>Price: ${price}</strong>
  377. <p>${description}</p>
  378. </div>
  379. `
  380. main.style.padding = "10px"
  381. }
  382. })
  383. store.subscribe(() => {
  384. const { login } = store.getState().promise
  385. const [, route, _id] = location.hash.split('/')
  386. let passInp, logInp
  387. if (!login?.payload && route === 'login') {
  388. console.log('hire');
  389. aside.innerHTML = ''
  390. main.innerHTML = `
  391. <div style="border: 1px solid black; padding: 10px">
  392. <button id="returnBtnLogin" style="font-size: smaller;">&#8656 назад</button>
  393. <input id="logInp" style="display:block; margin:10px" type="text" placeholder="login"/>
  394. <input id="passInp" style="display:block; margin:10px" type="text" placeholder="password"/>
  395. <button style="display:block; margin:0 auto">LOGIN</button>
  396. </div>
  397. `
  398. let returnBtn = document.getElementById('returnBtnLogin')
  399. logInp = document.getElementById('logInp')
  400. passInp = document.getElementById('passInp')
  401. returnBtn.onclick = () => {
  402. logBtn.disabled = false
  403. history.back()
  404. }
  405. logBtn.disabled = true
  406. }
  407. })
  408. store.subscribe(()=> {
  409. const {cart} = store.getState()
  410. let items = 0
  411. for(let item in cart) {
  412. items += cart[item].count
  413. }
  414. let itemCount = document.getElementById('itemCount')
  415. itemCount.innerText = items
  416. })
  417. window.onload = () => {
  418. location.href = "#/category/5dc49f4d5df9d670df48cc64"
  419. }