function createStore(reducer) { let state = reducer(undefined, {}) //стартовая инициализация состояния, запуск редьюсера со state === undefined let cbs = [] //массив подписчиков const getState = () => state //функция, возвращающая переменную из замыкания const subscribe = cb => (cbs.push(cb), //запоминаем подписчиков в массиве () => cbs = cbs.filter(c => c !== cb)) //возвращаем функцию unsubscribe, которая удаляет подписчика из списка const dispatch = action => { if (typeof action === 'function') { //если action - не объект, а функция return action(dispatch, getState) //запускаем эту функцию и даем ей dispatch и getState для работы } const newState = reducer(state, action) //пробуем запустить редьюсер if (newState !== state) { //проверяем, смог ли редьюсер обработать action state = newState //если смог, то обновляем state for (let cb of cbs) cb() //и запускаем подписчиков } } return { getState, //добавление функции getState в результирующий объект dispatch, subscribe //добавление subscribe в объект } } const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms)) const jwtDecode = token => { try { let arrToken = token.split('.') let base64Token = atob(arrToken[1]) return JSON.parse(base64Token) } catch (e) { console.log('Лажа, Бро ' + e); } } function authReducer(state, { type, token }) { if (!state) { if (localStorage.authToken) { type = 'AUTH_LOGIN' token = localStorage.authToken } else state = {} } if (type === 'AUTH_LOGIN') { localStorage.setItem('authToken', token) let payload = jwtDecode(token) if (typeof payload === 'object') { return { ...state, token, payload } } else return state } if (type === 'AUTH_LOGOUT') { localStorage.removeItem('authToken') return {} } return state } function cartReducer(state = {}, { type, good = {}, count = 1 }) { const { _id } = good const types = { CART_ADD() { count = +count if (!count) return state return { ...state, [_id]: { good, count: count + (state[_id]?.count || 0) } } }, CART_CHANGE() { count = +count if (!count) return state return { ...state, [_id]: { good, count: count } } }, CART_REMOVE() { let { [_id]: remove, ...newState } = state return { ...newState } }, CART_CLEAR() { return {} }, } if (type in types) { return types[type]() } return state } function promiseReducer(state = {}, { type, status, payload, error, name }) { if (type === 'PROMISE') { return { ...state, [name]: { status, payload, error } } } return state; } const combineReducers = (reducers) => (state = {}, action) => { const newState = {} for (const [reducerName, reducer] of Object.entries(reducers)) { const newSubState = reducer(state[reducerName], action) if (newSubState !== state[reducerName]) { newState[reducerName] = newSubState } } if (Object.keys(newState).length !== 0) { return { ...state, ...newState } } else { return state } } const combineReducer = combineReducers({ promise: promiseReducer, auth: authReducer, cart: cartReducer }) const actionAddCart = (good, count) => ({ type: 'CART_ADD', good, count }) const actionChangeCart = (good, count) => ({ type: 'CART_CHANGE', good, count }) const actionRemoveCart = good => ({ type: 'CART_REMOVE', good }) const actionCleanCart = () => ({ type: 'CART_CLEAR' }) const actionAuthLogin = token => ({ type: 'AUTH_LOGIN', token }) const actionAuthLogout = () => ({ type: 'AUTH_LOGOUT' }) const actionOrder = () => async (dispatch, getState) => { let { cart } = getState() const orderGoods = Object.entries(cart).map(([_id, { count }]) => ({ good: { _id }, count })) let result = await dispatch(actionPromise('order', gql(` mutation newOrder($order:OrderInput){ OrderUpsert(order:$order) { _id total } } `, { order: { orderGoods } }))) if (result?._id) { dispatch(actionCleanCart()) } } const actionPending = name => ({ type: 'PROMISE', status: 'PENDING', name }) const actionResolved = (name, payload) => ({ type: 'PROMISE', status: 'RESOLVED', name, payload }) const actionRejected = (name, error) => ({ type: 'PROMISE', status: 'REJECTED', name, error }) const actionPromise = (name, promise) => async dispatch => { dispatch(actionPending(name)) try { let data = await promise dispatch(actionResolved(name, data)) return data } catch (error) { dispatch(actionRejected(name, error)) } } const actionSearchGoods = (value) => actionPromise('sort', gql(`query gf($query: String){ GoodFind(query: $query){ _id, name, description, price, images{ _id, url } } }`, { query: JSON.stringify([ { $or: [{ title: value }, { name: value }, { description: value }] //регулярки пишутся в строках }, { sort: [{ title: 1 }] } //сортируем по title алфавитно ]) })) const actionRootCats = () => actionPromise('rootCats', gql(`query { CategoryFind(query: "[{\\"parent\\":null}]"){ _id name } }`)) const actionCatById = (_id) => actionPromise('catById', gql(`query catById($q: String){ CategoryFindOne(query: $q){ subCategories{name, _id} _id name goods { _id name price images { url } } } }`, { q: JSON.stringify([{ _id }]) })) const actionGoodById = (_id) => //добавить подкатегории actionPromise('goodById', gql(`query goodByID($q: String) { GoodFind(query: $q){ name _id description price images{url} } }`, { q: JSON.stringify([{ _id }]) })) const actionLogin = (login, password) => actionPromise('login', gql(`query NameForMe1($login:String, $password:String){ login(login:$login, password:$password) }`, { login, password })) const actionMyOrders = () => actionPromise('myOrders', gql(`query Order{ OrderGoodFind(query:"[{}]"){ good{ name _id} _id total price count } }`, {})) const actionFullLogin = (login, password) => async dispatch => { let token = await dispatch(actionLogin(login, password)) if (token) { dispatch(actionAuthLogin(token)) } } const actionRegister = (login, password) => actionPromise('register', gql(` mutation reg($login:String, $password:String){ UserUpsert(user:{ login:$login, password:$password, nick:$login}){ _id login } } `, { login, password })) const actionFullRegister = (login, password) => async dispatch => { await actionRegister(login, password) let token = await dispatch(actionLogin(login, password)) debugger if (token) { dispatch(actionAuthLogin(token)) } } const store = createStore(combineReducer) const getGQL = url => async (query, variables = {}) => { let obj = await fetch(url, { method: 'POST', headers: { "Content-Type": "application/json", Authorization: localStorage.authToken ? 'Bearer ' + localStorage.authToken : {}, }, body: JSON.stringify({ query, variables }) }) let a = await obj.json() if (!a.data && a.errors) throw new Error(JSON.stringify(a.errors)) return a.data[Object.keys(a.data)[0]] } const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua' const gql = getGQL(backURL + '/graphql'); store.dispatch(actionRootCats()) store.dispatch(actionGoodById()) // store.dispatch(actionAuthLogin(token)) // store.dispatch(actionPromise('delay2000', delay(1000))) window.onhashchange = () => { const [, route, _id] = location.hash.split('/') const routes = { category() { store.dispatch(actionCatById(_id)) }, good() { //задиспатчить actionGoodById store.dispatch(actionGoodById(_id)) }, login() { userAuthorizationFields(route) }, register() { userAuthorizationFields(route) }, order() { //задиспатчить actionGoodById renderOrder() }, dashboard() { store.dispatch(actionMyOrders()) } } if (route in routes) routes[route]() else { startPage() } } window.onhashchange() function startPage() { main.innerHTML = "" } //поля авторизации function userAuthorizationFields(key) { const userBox = document.createElement('div') userBox.setAttribute('id', 'userBox') const h2 = document.createElement('h2') const inputNick = document.createElement('input') const inputPassword = document.createElement('input') inputNick.type = 'text' inputPassword.type = 'password' const btnEnter = document.createElement('a') const btnClose = document.createElement('a') btnClose.onclick = () => { userBox.remove() overlay.style.display = 'none' } btnClose.innerText = 'X' btnClose.classList.add('close') btnClose.href = '#' btnEnter.href = '#' overlay.style.display = 'block' if (key === 'login') { h2.innerText = 'Log In' btnEnter.innerText = 'Log In' btnEnter.setAttribute('id', 'logIn') btnEnter.onclick = () => store.dispatch(actionFullLogin(inputNick.value, inputPassword.value)) } else { h2.innerText = 'Register' btnEnter.innerText = 'Register' btnEnter.setAttribute('id', 'register') btnEnter.onclick = () => store.dispatch(actionFullRegister(inputNick.value, inputPassword.value)) } userBox.append(h2) userBox.append(inputNick) userBox.append(btnClose) userBox.append(inputPassword) userBox.append(btnEnter) user.append(userBox) } //ссылки когда не авторизирован function noAuthorization() { const loginLink = document.createElement('a') loginLink.classList.add('user__link') loginLink.innerText = 'Log In' loginLink.href = '#/login' const registerLink = document.createElement('a') registerLink.href = '#/register' registerLink.innerText = 'Register' registerLink.classList.add('user__link') user.append(loginLink) user.append(registerLink) } // страница заказа function renderOrder() { const { cart, auth } = store.getState() const [, route, _id] = location.hash.split('/') main.innerHTML = '' if (Object.keys(cart).length !== 0 && route === 'order') { const orderTop = document.createElement('div') orderTop.classList.add('order-top') const orderCleanBtn = document.createElement('button') orderCleanBtn.classList.add('clean-order') orderCleanBtn.innerText = 'Clean order' orderCleanBtn.onclick = () => { store.dispatch(actionCleanCart()) main.innerHTML = '' } orderTop.append(orderCleanBtn) main.append(orderTop) for (const key in cart) { const { _id, name, price, images } = cart[key].good const divContainer = document.createElement('div') divContainer.classList.add('product-order__inner') const img = document.createElement('img') img.src = `${backURL}/${images[0].url}` const a = document.createElement('a') a.href = `#/good/${_id}` a.innerText = name const input = document.createElement('input') input.type = 'number' input.min = '1' input.value = cart[key].count input.oninput = () => { spanTotal.innerHTML = `Сумма: ${price * +input.value}$` store.dispatch(actionChangeCart(cart[key].good, input.value)) } const spanPrice = document.createElement('span') spanPrice.innerHTML = `Цена: ${price} $` const spanTotal = document.createElement('span') spanTotal.innerHTML = `Сумма: ${price * +input.value} $` const buttonRemove = document.createElement('button') buttonRemove.innerText = 'x' buttonRemove.onclick = () => { store.dispatch(actionRemoveCart(cart[key].good)) divContainer.remove() } divContainer.append(img) divContainer.append(a) divContainer.append(spanPrice) divContainer.append(input) divContainer.append(spanTotal) divContainer.append(buttonRemove) main.append(divContainer) } const orderSentBtn = document.createElement('button') orderSentBtn.innerText = 'Заказать' orderSentBtn.classList.add('order-sent__btn') if (auth?.token) { orderSentBtn.onclick = () => { store.dispatch(actionOrder()) main.innerText = ' Спасибо, заказ оформлен' } } else orderSentBtn.onclick = () => { const err = document.createElement('div') err.innerText = 'Sorry, please Log In or Register Now' err.style.color = '#ff0000' main.prepend(err) } main.append(orderSentBtn) } } store.dispatch(actionRootCats()) store.dispatch(actionGoodById()) // рисуем категории store.subscribe(() => { let a = Object.entries(store.getState().promise).map(t => t[1].status === 'PENDING') let ss = el => el === true a.some(ss) ? preLoader.style.display = 'block' : preLoader.style.display = 'none' }) store.subscribe(() => { const { rootCats } = store.getState().promise if (rootCats?.payload) { aside.innerHTML = '' for (const { _id, name } of rootCats?.payload) { const link = document.createElement('a') link.href = `#/category/${_id}` link.innerText = name aside.append(link) } } }) // рисуем продукты категории store.subscribe(() => { const { catById } = store.getState().promise const [, route, _id] = location.hash.split('/') if (catById?.payload && route === 'category') { const { name, subCategories } = catById.payload main.innerHTML = `
${price} $
Обзор: ${description}