index.js 17 KB

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