App.js 10 KB

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