123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633 |
- 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 в объект
- }
- }
- function combineReducers(reducers) {
- return (state={}, action) => {
- const newState = {}
- // перебрать все редьюсеры
- if (reducers) {
- for (const [reducerName, reducer] of Object.entries(reducers)) {
- const newSubState = reducer(state[reducerName], action)
- if (newSubState !== state[reducerName]) {
- newState[reducerName] = newSubState
- }
- }
- // если newState не пустой, то вернуть стейт в
- if (Object.keys(newState).length !== 0) {
- return {...state, ...newState}
- } else {
- return state
- }
- }
- }
- }
- const combinedReducer = combineReducers({promise: promiseReducer, auth: authReducer, cart: cartReducer})
- const store = createStore(combinedReducer)
- store.subscribe(() => console.log(store.getState()))
- function jwtDecode(token) {
- try {
- let decoded = JSON.parse(atob(token.split('.')[1]))
- return decoded
- } catch (err) {
- console.log(err)
- }
- }
- function authReducer(state, {type, token}) {
- if (!state) {
- if (localStorage.authToken) {
- token = localStorage.authToken
- type = 'AUTH_LOGIN'
- } else {
- return {}
- }
- }
- if (type === 'AUTH_LOGIN') {
- let payload = jwtDecode(token)
- if (typeof payload === 'object') {
- localStorage.authToken = token
- return {
- ...state,
- token,
- payload
- }
- } else {
- return state
- }
- }
- if (type === 'AUTH_LOGOUT') {
- delete localStorage.authToken
- return {}
- }
- return state
- }
- const actionAuthLogin = (token) => ({type: 'AUTH_LOGIN', token})
- const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'})
- function cartReducer (state={}, {type, good={}, count=1}) {
- if (!state) {
- return {}
- }
- // только если в функции задан count по умолчанию вызывать тут
- // а так лучше вызвать в типах add и change
- // count = +count
- // if (!count) {
- // return state
- // }
- const {_id} = good
- const types = {
- CART_ADD() {
- count = +count
- if (!count) {
- return state
- }
- return {
- ...state,
- [_id]: {good, count: (count + (state[_id]?.count || 0)) < 0 ? 0 : count + (state[_id]?.count || 0)}
- }
- },
- CART_CHANGE() {
- count = +count
- if (!count) {
- return state
- }
- return {
- ...state,
- [_id]: {good, count: count < 0 ? 0 : count}
- }
- },
- CART_REMOVE() {
- let { [_id]: removed, ...newState } = state
- return newState
- },
- CART_CLEAR() {
- return {}
- },
- }
- if (type in types) {
- return types[type]()
- }
- return state
- }
- const actionCartAdd = (good) => ({type: 'CART_ADD', good})
- const actionCartChange = (good, count) => ({type: 'CART_CHANGE', good, count})
- const actionCartRemove = (good) => ({type: 'CART_REMOVE', good})
- const actionCartClear = () => ({type: 'CART_CLEAR'})
- store.dispatch(actionCartAdd({_id: '111111'}))
- store.dispatch(actionCartChange({_id: '111111'}, 10))
- store.dispatch(actionCartAdd({_id: '22222'}))
- store.dispatch(actionCartRemove({_id: '22222'}))
- store.dispatch(actionCartClear())
- function promiseReducer(state={}, {type, status, payload, error, name}) {
- if (!state) {
- return {}
- }
- if (type === 'PROMISE') {
- return {
- ...state,
- [name]: {
- status: status,
- payload : payload,
- error: error,
- }
- }
- }
- return state
- }
- 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 getGQL = url =>
- async (query, variables={}) => {
- let obj = await fetch(url, {
- method: 'POST',
- headers: {
- "Content-Type": "application/json",
- ...(localStorage.authToken ? {Authorization: "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))
- } else {
- return a.data[Object.keys(a.data)[0]]
- }
- }
- const backURL = 'http://shop-roles.asmer.fs.a-level.com.ua/'
- const gql = getGQL(backURL + 'graphql');
- const actionOrder = () => (
- async (dispatch, getState) => {
- let {cart} = getState()
- //магия по созданию структуры вида
- //let orderGoods = [{good: {_id}, count}, {good: {_id}, count} .......]
- //из структуры вида
- //{_id1: {good, count},
- //_id2: {good, count}}
- const orderGoods = Object.entries(cart)
- .map(([_id, {good, 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(actionCartClear())
- }
- })
-
- const actionLogin = (login, password) => (
- actionPromise('login', gql(`query log($login: String, $password: String) {
- login(login: $login, password: $password)
- }`, {login, password}))
- )
- const actionFullLogin = (login, password) => (
- async (dispatch) => {
- let token = await dispatch(actionLogin(login, password))
- if (token) {
- // console.log(token)
- dispatch(actionAuthLogin(token))
- }
- }
- )
- const actionRegister = (login, password) => (
- actionPromise('register', gql(`mutation reg($user:UserInput) {
- UserUpsert(user:$user) {
- _id
- }
- }
- `, {user: {login, password}})
- )
- )
- const actionFullRegister = (login, password) => (
- async (dispatch) => {
- let regId = await dispatch(actionRegister(login, password))
- if (regId) {
- // console.log(regId)
- dispatch(actionFullLogin(login, password))
- }
- }
- )
- 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){
- _id name goods {
- _id name price images {
- url
- }
- }
- subCategories {
- _id name
- }
- }
- }`, {q: JSON.stringify([{_id}])}))
- )
- const actionGoodById = (_id) => (
- actionPromise('goodById', gql(`query goodById($q: String) {
- GoodFindOne(query: $q) {
- _id name price description images {
- url
- }
- }
- }`, {q: JSON.stringify([{_id}])}))
- )
- const actionGoodsByUser = () => (
- actionPromise('goodByUser', gql(`query oUser($query: String) {
- OrderFind(query:$query){
- _id orderGoods{
- price count total good{
- _id name categories{
- name
- }
- images {
- url
- }
- }
- }
- owner {
- _id login
- }
- }
- }`,
- {query: JSON.stringify([{}])}))
- )
-
- store.dispatch(actionRootCats())
- store.subscribe(() => {
- const {promise} = store.getState()
- const {rootCats} = promise
- if (rootCats?.payload) {
- aside.innerHTML = ''
- const regBtn = document.createElement('a')
- regBtn.href = `#/register`
- regBtn.innerText = 'Register'
- const loginBtn = document.createElement('a')
- loginBtn.href = `#/login`
- loginBtn.innerText = 'Login'
- const logoutBtn = document.createElement('button')
- logoutBtn.innerText = 'Logout'
- aside.append(regBtn, loginBtn, logoutBtn)
- logoutBtn.onclick = () => {
- store.dispatch(actionAuthLogout())
- }
- for (const {_id, name} of rootCats?.payload) {
- const link = document.createElement('a')
- link.href = `#/category/${_id}`
- link.innerText = name
- aside.append(link)
- }
- }
- })
- function createForm(parent, type, callback) {
- parent.innerHTML = `
- <input id="login${type}" type="text"/>
- <input id="pass${type}" type="password"/>
- <button id="btn${type}">${type}</button>
- `
- return () => window[`btn${type}`].onclick = () => {
- store.dispatch(callback(window[`login${type}`].value, window[`pass${type}`].value))
- window[`pass${type}`].value = ''
- }
- }
- const createCartPage = (parent) => {
- parent.innerHTML = '';
- const {cart} = store.getState();
- const clearBtn = document.createElement('button');
- clearBtn.innerText = "ОЧИСТИТЬ КОРЗИНУ";
- if(Object.keys(cart).length !== 0) {
- main.append(clearBtn);
- }
- clearBtn.onclick = () => {
- store.dispatch(actionCartClear());
- }
- for(const item in cart) {
- const {good} = cart[item];
- const {count, good: {_id: id, name: name, price: price, images: [{url}]}} = cart[item];
- const card = document.createElement('div');
- card.innerHTML = `
- <div>
- <p>${name}</p>
- <img src="${backURL}/${url}">
- <p>${count}</p>
- <p>${price} грн</p>
- </div>
- `;
- const changeCount = document.createElement('input');
- changeCount.type = 'number';
- changeCount.value = count;
- card.append(changeCount);
- changeCount.oninput = () => {
- store.dispatch(actionCartChange(good, changeCount.value))
- };
- const deleteGood = document.createElement('button');
- deleteGood.innerText = 'X';
- deleteGood.style.display = 'block';
- card.append(deleteGood);
- deleteGood.onclick = () => {
- store.dispatch(actionCartRemove(good))
- }
- parent.append(card);
- }
- const sendOrder = document.createElement('button');
- sendOrder.innerText = "ОФОРМИТЬ ЗАКАЗ";
- if(Object.keys(cart).length !== 0) {
- main.append(sendOrder);
- }
- sendOrder.onclick = () => {
- store.dispatch(actionOrder())
- }
- }
- // location.hash - адресная строка после решетки
- window.onhashchange = () => {
- const [,route, _id] = location.hash.split('/')
- const routes = {
- category(){
- store.dispatch(actionCatById(_id))
- console.log('страница категорий')
- },
- good(){
- store.dispatch(actionGoodById(_id))
- console.log('страница товара')
- },
- register(){
- let goRegister = createForm(main, 'Register', actionFullRegister)
- goRegister()
- },
- login(){
- let goLogin = createForm(main, 'Login', actionFullLogin)
- goLogin()
- },
- orders(){
- store.dispatch(actionGoodsByUser())
- },
- cart(){
- createCartPage(main)
- },
- }
- if (route in routes) {
- routes[route]()
- }
- }
- store.subscribe(() => {
- const [,route] = location.hash.split('/')
- if (route === 'cart') {
- createCartPage(main);
- }
- })
- window.onhashchange()
- store.subscribe(() => {
- const {promise} = store.getState()
- const {catById} = promise
- const [,route, _id] = location.hash.split('/')
- if (catById?.payload && route === 'category'){
- const {name} = catById.payload;
- main.innerHTML = `<h1>${name}</h1>`
-
- if (catById.payload.subCategories) {
- for(const {_id, name} of catById.payload.subCategories) {
- const link = document.createElement('a');
- link.href = `#/category/${_id}`;
- link.innerText = name;
- main.append(link);
- }
- }
-
- if (catById.payload.goods) {
- for (const good of catById.payload.goods){
- const {_id, name, price, images} = good
- const card = document.createElement('div')
- card.innerHTML = `<h2>${name}</h2>
- <img src="${backURL}/${images[0].url}" />
- <strong>${price} грн</strong>
- <br>
- <a href="#/good/${_id}">Перейти на страницу товара</a>
- `
- const btnCart = document.createElement('button')
- btnCart.innerText = 'Добавить в корзину'
- btnCart.onclick = () => {
- store.dispatch(actionCartAdd(good))
- }
- card.append(btnCart)
- main.append(card)
- }
- }
- }
- })
- store.subscribe(() => {
- const {promise} = store.getState()
- const {goodById} = promise
- const [,route, _id] = location.hash.split('/');
- if (goodById?.payload && route === 'good') {
- main.innerHTML = '';
- const good = goodById.payload;
- const {_id, name, images, price, description} = good
- const card = document.createElement('div');
- card.innerHTML = `<h2>${name}</h2>
- <img src="${backURL}/${images[0].url}" />
- <strong>${price} грн</strong>
- <h2>${description}</h2>
- `;
- const btnCart = document.createElement('button')
- btnCart.innerText = 'Добавить в корзину'
- btnCart.onclick = () => {
- store.dispatch(actionCartAdd(good))
- }
- card.append(btnCart)
- main.append(card);
- }
- }
- )
- store.subscribe(() => {
- const {auth} = store.getState()
- const {payload} = auth
- if (payload?.sub ) {
- topContaner.innerHTML = ''
- const {id, login} = payload.sub
- const name = document.createElement('div')
- name.innerText = `ПРИВЕТ ${login}`
- topContaner.append(name)
- const myOrders = document.createElement('a')
- myOrders.innerText = 'Мои заказы'
- myOrders.href = `#/orders/${id}`
- topContaner.append(myOrders)
- } else {
- topContaner.innerHTML = ''
- }
- })
- store.subscribe(() => {
- const {promise} = store.getState()
- const {goodByUser} = promise
- const [,route] = location.hash.split('/')
- if (goodByUser?.payload && route === 'orders'){
- main.innerHTML = ''
- if (goodByUser.payload) {
- let totalMoney = 0
- for (const order of goodByUser.payload) {
- if (order.orderGoods) {
- for (const {price, count, total, good} of order.orderGoods) {
- if (price !== null && count !== null && total !== null && good !== null) {
- totalMoney += total
- const {_id, name, images} = good
- const card = document.createElement('div')
- card.innerHTML = `<h2>${name}</h2>
- <img src="${backURL}/${images[0].url}" />
- <strong>Куплено ${count} по ${price} грн. Итого: ${total} грн</strong>
- <br>
- <a href="#/good/${_id}">Перейти на страницу товара</a>
- `
- main.append(card)
- }
- }
- }
- }
- const totalBlock = document.createElement('b')
- totalBlock.innerText = 'Итого потрачено: ' + totalMoney + ' грн'
- main.append(totalBlock)
- }
- }
- })
- store.subscribe(() => {
- const {cart} = store.getState()
- let counter = 0;
-
- for (const key in cart) {
- counter += cart[key].count
- }
- cartIcon.innerText = counter
- })
|