App.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import logo from './logo.svg';
  2. import './App.scss';
  3. import thunk from 'redux-thunk';
  4. import {createStore, combineReducers, applyMiddleware} from 'redux';
  5. import {Provider, connect} from 'react-redux';
  6. import {useState} from 'react';
  7. const actionPending = name => ({type: 'PROMISE', status: 'PENDING', name});
  8. const actionResolved = (name, payload) => ({type: 'PROMISE', status: 'RESOLVED', name, payload});
  9. const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error});
  10. const actionPromise = (name, promise) =>
  11. async dispatch => {
  12. dispatch(actionPending(name)); // 1. {delay1000: {status: 'PENDING'}}
  13. try {
  14. let payload = await promise;
  15. dispatch(actionResolved(name, payload));
  16. return payload;
  17. } catch (error) {
  18. dispatch(actionRejected(name, error));
  19. }
  20. };
  21. const getGQL = url =>
  22. (query, variables = {}) =>
  23. fetch(url, {
  24. //метод
  25. method: 'POST',
  26. headers: {
  27. //заголовок content-type
  28. 'Content-Type': 'application/json',
  29. ...(localStorage.authToken ? {'Authorization': 'Bearer ' + localStorage.authToken} :
  30. {})
  31. },
  32. //body с ключами query и variables
  33. body: JSON.stringify({query, variables})
  34. })
  35. .then(res => res.json())
  36. .then(data => {
  37. if (data.errors && !data.data)
  38. throw new Error(JSON.stringify(data.errors));
  39. return data.data[Object.keys(data.data)[0]];
  40. });
  41. const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua';
  42. const gql = getGQL(backendURL + '/graphql');
  43. function jwtDecode(token) {
  44. try {
  45. let decoded = token.split('.');
  46. decoded = decoded[1];
  47. decoded = atob(decoded);
  48. decoded = JSON.parse(decoded);
  49. return decoded;
  50. } catch (e) {
  51. return;
  52. }
  53. }
  54. //скопировать
  55. //3 редьюсера
  56. //экшоны к ним
  57. //
  58. const actionRootCats = () =>
  59. actionPromise('rootCats', gql(`query {
  60. CategoryFind(query: "[{\\"parent\\":null}]"){
  61. _id name
  62. }
  63. }`));
  64. const actionCartAdd = (good, count = 1) => ({type: 'CART_ADD', good, count});
  65. const actionCartRemove = (good, count = 1) => ({type: 'CART_REMOVE', good, count});
  66. const actionCartChange = (good, count = 1) => ({type: 'CART_CHANGE', good, count});
  67. const actionCartClear = (good, count = 1) => ({type: 'CART_CLEAR', good, count});
  68. function cartReducer(state = {}, {type, good = {}, count = 1}) {
  69. const {_id} = good;
  70. const types = {
  71. CART_ADD() {
  72. return {
  73. ...state,
  74. [_id]: {good, count: count + (state[_id]?.count || 0)}
  75. };
  76. },
  77. CART_REMOVE() {
  78. let newState = {...state};
  79. delete newState[_id];
  80. return {
  81. ...newState
  82. };
  83. },
  84. CART_CHANGE() {
  85. return {
  86. ...state,
  87. [_id]: {good, count}
  88. };
  89. },
  90. CART_CLEAR() {
  91. return {};
  92. },
  93. };
  94. if (type in types)
  95. return types[type]();
  96. return state;
  97. }
  98. function authReducer(state, {type, token}) {
  99. if (!state) {
  100. if (localStorage.authToken) {
  101. type = 'AUTH_LOGIN';
  102. token = localStorage.authToken;
  103. } else {
  104. return {};
  105. }
  106. }
  107. if (type === 'AUTH_LOGIN') {
  108. let auth = jwtDecode(token);
  109. if (auth) {
  110. localStorage.authToken = token;
  111. return {token, payload: auth};
  112. }
  113. }
  114. if (type === 'AUTH_LOGOUT') {
  115. localStorage.authToken = '';
  116. return {};
  117. }
  118. return state;
  119. }
  120. function promiseReducer(state = {}, {type, name, status, payload, error}) {
  121. if (type === 'PROMISE') {
  122. return {
  123. ...state,
  124. [name]: {status, payload, error}
  125. };
  126. }
  127. return state;
  128. }
  129. // Actions =============================
  130. // Логин и логаут
  131. const actionAuthLogin = (token) => ({type: 'AUTH_LOGIN', token});
  132. const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'});
  133. const actionLogin = (login = 'tst', password = '123') =>
  134. actionPromise('login', gql(`query ($login:String, $password:String){ login(login:$login, password:$password)}`, {
  135. 'login': login,
  136. 'password': password
  137. }));
  138. const actionFullLogin = (login = 'tst', password = '123') =>
  139. async dispatch => {
  140. let token = await dispatch(actionLogin(login, password));
  141. console.log(token);
  142. if (token) {
  143. dispatch(actionAuthLogin(token));
  144. }
  145. };
  146. // Регистрация
  147. const actionRegister = (login = 'tst', password = '123') =>
  148. actionPromise('login', gql(`mutation reg($login:String, $password:String) {
  149. UserUpsert(user:{login:$login, password:$password, nick:$login}){
  150. _id login
  151. }
  152. }`, {'login': login, 'password': password}));
  153. const actionFullRegister = (login = 'tst', password = '123') =>
  154. async dispatch => {
  155. console.log(login, password);
  156. await dispatch(actionRegister(login, password));
  157. await dispatch(actionFullLogin(login, password));
  158. };
  159. // Корневые категории
  160. // Товары категории
  161. const actionCatById = (_id) =>
  162. actionPromise('catById', gql(`query ($q: String){
  163. CategoryFindOne(query: $q){
  164. _id name goods {
  165. _id name price images {
  166. url
  167. }
  168. }
  169. subCategories {
  170. _id name
  171. }
  172. }
  173. }`, {q: JSON.stringify([{_id}])}));
  174. const actionGoodById = (_id) =>
  175. actionPromise('goodById', gql(`query ($good:String) {
  176. GoodFindOne(query:$good) {
  177. _id name price images {
  178. url
  179. }
  180. }
  181. }`, {good: JSON.stringify([{_id}])}));
  182. const store = createStore(combineReducers(
  183. {
  184. promise: promiseReducer,
  185. auth: authReducer,
  186. cart: cartReducer
  187. }),
  188. applyMiddleware(thunk));
  189. store.subscribe(() => console.log(store.getState()));
  190. store.dispatch(actionRootCats());
  191. store.dispatch(actionCatById('5dc458985df9d670df48cc47'));
  192. const Logo = () =>
  193. <img src={logo} className="Logo" alt="logo"/>;
  194. const Header = () =>
  195. <header className="header">
  196. <Logo/>
  197. <CKoshik/>
  198. </header>;
  199. const CategoryListItem = ({_id, name}) =>
  200. <li><a href={`#/category/${_id}`}>{name}</a></li>;
  201. const CategoryList = ({cats}) => {
  202. return (
  203. <ul>
  204. {cats.map((item) => <CategoryListItem key={item._id} {...item}/>)}
  205. </ul>
  206. );
  207. };
  208. const CCategoryList = connect(state => ({cats: state.promise.rootCats?.payload || []}))(CategoryList);
  209. const Aside = () =>
  210. <aside className="aside">
  211. <CCategoryList/>
  212. </aside>;
  213. const GoodCard = ({good: {_id, name, price, images}, onAdd}) =>
  214. <li className="GoodCard">
  215. <h2>{name}</h2>
  216. {images && images[0] && images[0].url && <img src={backendURL + '/' + images[0].url}/>}
  217. <strong>{price} грн</strong>
  218. <button onClick={() => onAdd({_id, name, price, images})}>+</button>
  219. </li>;
  220. const CGoodCard = connect(null, {onAdd: actionCartAdd})(GoodCard);
  221. const Koshik = ({cart}) => {
  222. let goodsInCart = cart;
  223. let allGoodsInCart = 0;
  224. for (let key in goodsInCart) {
  225. allGoodsInCart += goodsInCart[key].count;
  226. }
  227. return (
  228. <h2 className="koshikCounter">В корзине:{allGoodsInCart}</h2>
  229. );
  230. };
  231. const CKoshik = connect(({cart}) => ({cart}))(Koshik);
  232. const Category = ({cat: {name, goods = []} = {}}) => {
  233. return (
  234. <div className="Category">
  235. <h1>{name}</h1>
  236. <ul className="ul">
  237. {goods.map(good => <CGoodCard key={good._id} good={good}/>)}
  238. </ul>
  239. </div>
  240. );
  241. };
  242. const CCategory = connect(state => ({cat: state.promise.catById?.payload || {}}))(Category);
  243. const Cart = ({cart, onCartChange, onCartRemove}) => {
  244. const error = typeof cart === 'undefined';
  245. return (
  246. <div className="Cart">
  247. <h1>Корзина</h1>
  248. <div className="containerForCart">
  249. <div className="wrapperForName">
  250. {error === false &&
  251. (cart.map((good) => {
  252. return (
  253. <div className="name" key={good.good.name}>{good.good.name}</div>
  254. );
  255. })
  256. )
  257. }
  258. </div>
  259. <div className="wrapperForCount">
  260. {error === false &&
  261. (cart.map((good) => {
  262. return <input
  263. className="count"
  264. type="number"
  265. defaultValue={good.count}
  266. onChange={(e) => {
  267. onCartChange(good.good, +e.target.value);
  268. }
  269. }
  270. key={good.good._id}
  271. />;
  272. })
  273. )}
  274. </div>
  275. <div className="wrapperForName">
  276. {error === false &&
  277. (cart.map((good) => {
  278. return (
  279. <button key={good.good._id} onClick={() => onCartRemove(good.good, good.count)
  280. }>
  281. Удалить {good.good.name}</button>);
  282. })
  283. )
  284. }
  285. </div>
  286. </div>
  287. </div>
  288. );
  289. };
  290. const CCart = connect(
  291. state => ({cart: Object.values(state.cart) || []}),
  292. {
  293. onCartChange: actionCartChange,
  294. onCartRemove: actionCartRemove
  295. })(Cart);
  296. const LoginForm = ({onCartLogin}) => {
  297. const [login, setLogin] = useState('');
  298. const [password, setPassword] = useState('');
  299. const isDisabled = login === '' || password === '';
  300. console.log(login, password, isDisabled)
  301. const onChange = (event) => {
  302. event.target.name === 'login' ? setLogin(event.target.value) : setPassword(event.target.value);
  303. };
  304. return (
  305. <div className="inputWrapper">
  306. <h1>Регистрация</h1>
  307. <input
  308. className="inputLogin"
  309. name="login"
  310. style={{borderColor: isDisabled ? 'red' : ''}}
  311. placeholder="введите логин"
  312. type="text"
  313. onChange={onChange}
  314. />
  315. <input
  316. className="inputPsw"
  317. name="password"
  318. style={{borderColor: isDisabled ? 'red' : ''}}
  319. placeholder="введите пароль"
  320. type="password"
  321. onChange={onChange}
  322. />
  323. <button
  324. className="buttonLogin"
  325. disabled={isDisabled}
  326. onClick={
  327. () => {
  328. onCartLogin(login, password);
  329. }}>Login
  330. </button>
  331. </div>
  332. );
  333. };
  334. const CLoginForm = connect(
  335. null,
  336. {
  337. onCartLogin: actionFullRegister
  338. })(LoginForm);
  339. const Main = () =>
  340. <main className="main">
  341. <Aside/>
  342. <Content>
  343. <CCategory/>
  344. <CLoginForm/>
  345. <CCart/>
  346. </Content>
  347. </main>;
  348. const Content = ({children}) =>
  349. <div className="Content">
  350. {children}
  351. </div>;
  352. const Footer = () =>
  353. <footer className="Footer">
  354. <Logo/>
  355. </footer>;
  356. //import {Provider, connect} from 'react-redux';
  357. function App() {
  358. return (
  359. <Provider store={store}>
  360. <div className="App">
  361. <Header/>
  362. <Main/>
  363. <Footer/>
  364. </div>
  365. </Provider>
  366. );
  367. }
  368. export default App;