123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414 |
- import logoDefault from './logo.svg';
- import './App.css';
- import {Provider, connect} from 'react-redux';
- import {createStore, combineReducers, applyMiddleware} from 'redux';
- import thunk from 'redux-thunk';
- 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
- }
- const actionAuthLogin = token => ({ type: 'AUTH_LOGIN', token })
- const actionAuthLogout = () => ({ type: 'AUTH_LOGOUT' })
- const actionLogin = (login, password) =>
- actionPromise('login', gql(`query NameForMe1($login:String, $password:String){
- login(login:$login, password:$password)
- }`, { login, password }))
- 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
- }
- const actionCartAdd = (good, count=1) => ({type: "CART_ADD", good, count});
- function promiseReducer(state = {}, { type, status, payload, error, name }) {
- if (type === 'PROMISE') {
- return {
- ...state,
- [name]: { status, payload, 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",
- 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');
- 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 store = createStore(combineReducers({promise: promiseReducer,
- auth: authReducer,
- cart: cartReducer}),
- applyMiddleware(thunk))
- store.subscribe(()=>console.log(store.getState()))
- store.dispatch(actionRootCats())
- store.dispatch(actionCatById('5dc49f4d5df9d670df48cc64'))
- const Logo = ({logo=logoDefault}) =>
- <a href='#' className='Logo'>
- <img src={logo} />
- </a>
- const KoshikGood = ({obj: {good: {_id, name, price, images}={}, count=1}}) => {
- console.log(name);
- console.log(count)
- return(
- <div className='GoodCard2'>
- <p>{name}</p>
- {images && images[0] && images[0].url && <img src={backURL+'/'+images[0].url} />}
- <p><input type='number' value={count} /></p>
- <p><strong>{price}</strong></p>
- </div>
- )
- }
- const KoshikGoods = ({goods}) =>{
- console.log(goods);
- return(
- <div className='GoodCard'>
- <h1>Корзина</h1>
- {Object.entries(goods).map(good2 =>{
- console.log(good2);
- return(
- <KoshikGood obj={good2[1]}/>
- )
- })}
- </div>
- )
- }
- const CKoshikGoods = connect(state => ({goods: state.cart}))(KoshikGoods)
- const Koshik = ({cart}) =>{
- let count = 0;
- let sum = Object.entries(cart).map(([, val]) => val.count);
- count = sum.reduce((a, b) => a + b, 0);
- return(
- <div>
- <div className='Koshik'>{count}</div>
- </div>
- )
- }
- const CKoshik = connect(({cart}) => ({cart}))(Koshik)
- const Header = ({logo=logoDefault}) =>
- <header>
- <Logo logo={logo} />
- <CKoshik />
- <CKoshikGoods />
- </header>
- const Footer = ({logo=logoDefault}) =>
- <footer>
- <Logo logo={logo} /> />
- </footer>
- const defaultRootCats = [
- {
- "_id": "5dc49f4d5df9d670df48cc64",
- "name": "Airconditions"
- },
- {
- "_id": "5dc458985df9d670df48cc47",
- "name": " Smartphones"
- },
- {
- "_id": "5dc4b2553f23b553bf354101",
- "name": "Крупная бытовая техника"
- },
- {
- "_id": "5dcac1b56d09c45440d14cf8",
- "name": "Макароны"
- }
- ]
- const RootCategory = ({cat:{_id,name}={}}) =>
- <li>
- <a href={`#/${_id}`}>{name}</a>
- </li>
- const RootCategories = ({cats=defaultRootCats}) =>
- <ul>
- {cats.map(cat=> <RootCategory cat={cat} />)}
- </ul>
- const CRootCategories = connect(state=>({cats: state.promise.rootCats?.payload || []}))(RootCategories)
- const Aside =()=>
- <aside>
- <CRootCategories />
- </aside>
- const Content =({children})=>
- <div className='Content'>
- {children}
- </div>
- const defaultCat = {
- "subCategories": null,
- "_id": "5dc458985df9d670df48cc47",
- "name": " Smartphones",
- "goods": [
- {
- "_id": "5dc4a3e15df9d670df48cc6b",
- "name": "Apple iPhone 11 Pro Max 64GB Gold",
- "price": 1500,
- "images": [
- {
- "url": "images/b599634ebfecf2a19d900e22434bedbd"
- }
- ]
- },
- {
- "_id": "5dc4a4365df9d670df48cc6c",
- "name": "Apple iPhone XS Max 256GB Gold",
- "price": 1300,
- "images": [
- {
- "url": "images/63c4a052377862494e33746b375903f6"
- }
- ]
- },
- {
- "_id": "61b1056cc750c12ba6ba4522",
- "name": "iPhone ",
- "price": 1000,
- "images": [
- {
- "url": "images/cc23c15a3ae1ac60582785ebf9b3d207"
- }
- ]
- },
- {
- "_id": "61b105f9c750c12ba6ba4524",
- "name": "iPhone ",
- "price": 1200,
- "images": [
- {
- "url": "images/50842a3af34bfa28be037aa644910d07"
- }
- ]
- },
- {
- "_id": "61b1069ac750c12ba6ba4526",
- "name": "iPhone ",
- "price": 1000,
- "images": [
- {
- "url": "images/d12b07d983dac81ccad404582a54d8be"
- }
- ]
- },
- {
- "_id": "61b23f94c750c12ba6ba472a",
- "name": "name1",
- "price": 1214,
- "images": [
- {
- "url": null
- }
- ]
- },
- {
- "_id": "61b23fbac750c12ba6ba472c",
- "name": "smart",
- "price": 1222,
- "images": [
- {
- "url": "images/871f4e6edbf86c35f70b72dcdebcd8b2"
- }
- ]
- }
- ]
- }
- const SubCategories = ({cats}) =>
- <></>
- const GoodCard = ({good: {_id,name,price,images}={}, onCartAdd}) =>
- <div className='GoodCard'>
- <h2>{name}</h2>
- {images && images[0] && images[0].url && <img src={backURL+'/'+images[0].url} />}
- <strong>{price}</strong>
- <button onClick={()=>onCartAdd({_id,name,price,images})}>+</button>
- </div>
- const CGoodCard = connect(null, {onCartAdd: actionCartAdd})(GoodCard)
- const Category = ({cat:{_id,name,goods,price,subCategories}=defaultCat}) =>
- <div className="Category">
- <h1>{name}</h1>
- {subCategories && <SubCategories cats={subCategories} />}
- {goods.map(good=> <CGoodCard good={good} />)}
- </div>
- const CCategory = connect(state=>({cat: state.promise.catById?.payload}))(Category)
- const Main = ()=>
- <main>
- <Aside />
- <Content>
- <CCategory />
- </Content>
- </main>
- const JSONTest = ({data}) =>
- <pre>
- {JSON.stringify(data,null,4)}
- </pre>
- const ReduxJSON = connect(state => ({data:state.promise}))(JSONTest)
- const ListItem = ({item}) =>
- <li>{item}</li>
- const List = ({data=["пиво","чипсы","сиги"]}) =>
- <ul>
- {data.map(item=><ListItem item={item} />)}
- </ul>
- function App() {
- return (
- <Provider store={store}>
- <div className="App">
- <Header />
- <Main />
- <Footer />
- </div>
- </Provider>
- );
- }
- export default App;
|