Browse Source

added half of search, have some bugs

kurkabein 2 years ago
parent
commit
fc81593b2e
2 changed files with 95 additions and 16 deletions
  1. 1 1
      GraphQl_and_updated_redux/index.html
  2. 94 15
      GraphQl_and_updated_redux/main.js

+ 1 - 1
GraphQl_and_updated_redux/index.html

@@ -20,7 +20,7 @@
     </style>
 </head>
 <body>
-    <header>
+    <header id="header">
         <div id='cartIcon'></div>
     </header>
     <div id='mainContainer'>

+ 94 - 15
GraphQl_and_updated_redux/main.js

@@ -333,10 +333,40 @@ const actionAllOrders = () =>
             OrderFind(query:"[{}]"){
               _id total
               orderGoods{
-                count total good{name}
+                count total good{name,price,
+                images{
+                  url
+                }}
               }
             }
           }`))
+const actionCreateOrder = () => async (dispatch) =>{
+    let orderGoods = [];
+    Object.entries(store.getState().cart).map(([_id,{count}])=>orderGoods.push({"count":count,"good":{_id:_id}}))
+    actionPromise('createOrder',gql(`mutation newOrder($order:OrderInput){
+        OrderUpsert(order:$order){
+          _id total
+        }
+      }`,{order:{orderGoods}}));
+     await store.dispatch(actionCartClean());
+}
+
+const actionSearchGood = (good) => 
+    actionPromise('searchGood', gql(`query gf($query: String){
+        GoodFind(query: $query){
+            _id, name, description, price, images{
+                _id, url
+            }
+        }
+    }`, {query: JSON.stringify([
+                {
+                    $or: [{name: `/${good}/`}, {description: `/${good}/`}] //регулярки пишутся в строках
+                },
+                {
+                    sort: [{name: 1}]} //сортируем по title алфавитно
+                ])
+    }))
+
 store.dispatch(actionRootCats())
     
 store.subscribe(() => {
@@ -480,7 +510,21 @@ window.onhashchange = () => {
                     main.append(goods);
                 
                 }
+                let orderButton = document.createElement('button');
+                orderButton.innerText = 'Order';
+                orderButton.onclick = () => {
+                    store.dispatch(actionCreateOrder());
+                    window.onhashchange()
+                    cartIcon.innerHTML = `Cart`
+            }
+                if(localStorage.authToken && Object.keys(cart).length !== 0){
+                    orderButton.disabled = ""
+                } else {
+                    orderButton.disabled = "true"
+                }
+                main.append(orderButton);
                 }
+              
             }
         }
         if (route in routes)
@@ -562,10 +606,10 @@ store.subscribe(() => {
     }
 
 })
-store.subscribe(() => {
+store.subscribe(async() => {
                 const[,route,id] = location.hash.split('/')
-                const {promise: {allOrders}} = store.getState();
-                if(route === 'dashboard'){
+                const {promise: {allOrders}} = await store.getState();
+                if(route === 'dashboard' && allOrders.payload){
                     main.innerHTML = `<h1>Dashboard</h1>`
                     for(const{_id,total,orderGoods} of allOrders.payload){
                        let order = document.createElement('div');
@@ -575,17 +619,13 @@ store.subscribe(() => {
                        totalCost.innerText = `${total}`
                        order.append(idOfOrder);
                        order.append(totalCost);
-                       for(const{count,good,totall} of orderGoods){
+                       for(const{count,total,good} of orderGoods){
                            let card = document.createElement('div');
-                           let counted = document.createElement('label');
-                           counted.innerHtml = `${count}`
-                           let totaled = document.createElement('label');
-                           totaled.innerHtml = `${totall}`
-                           let name = document.createElement('h2');
-                           name.innerText = `${good.name}`
-                           card.append(count);
-                           card.append(total);
-                           card.append(name);
+                           card.innerHTML = `<h2 id="name">${good.name}</h2>
+                                            <p id="counted">${count}</p>
+                                            <p id="totaled">${total}</p>
+                                            <img src="${backendURL}/${good.images[0].url}"> 
+                           `
                            order.append(card);
                        }
                        
@@ -593,6 +633,35 @@ store.subscribe(() => {
                         main.append(order);         
                     }
                 }
+})
+let inputSearch = document.createElement('input');
+inputSearch.type = "text";
+let header = document.getElementById('header');
+header.append(inputSearch);
+let divWithGood = document.createElement('div');
+divWithGood.style.display = 'none';
+header.append(divWithGood); 
+function render(parent,data){
+    console.log(data);
+}
+store.subscribe(() => {
+    let re = /\s* \s*/;
+    inputSearch.oninput = () => {
+            let newStr = inputSearch.value.trim().split(re).join("|");
+            store.dispatch(actionSearchGood(newStr));
+        }   
+    inputSearch.onfocus = () => {
+        divWithGood.style.display = 'block';
+        const searchGood = store.getState().promise.searchGood;
+        render(divWithGood,searchGood);
+
+    }
+    inputSearch.blur = () => {
+        divWithGood.style.display = 'none';
+        render(divWithGood,searchGood);
+    }
+
+
 })
     let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWJiNjNjOWM3NTBjMTJiYTZiYTRiMzgiLCJsb2dpbiI6IkFub24iLCJhY2wiOlsiNjFiYjYzYzljNzUwYzEyYmE2YmE0YjM4IiwidXNlciJdfSwiaWF0IjoxNjQwMjAwNTU2fQ.P_JXFko7OFObxVn8uB6TR3R1V9aB1MMQrgX58MpEq5E';
     /* store.dispatch(actionPromise('delay1000', delay(1000)))
@@ -611,4 +680,14 @@ store.subscribe(() => {
     store.dispatch(actionRegister('aufff', '123456')); */
     
     
-    /* const combinedStore = createStore(combineReducers({promise: promiseReducer, auth: authReducer})) */
+    /* const combinedStore = createStore(combineReducers({promise: promiseReducer, auth: authReducer})) */
+
+ //search
+//  let re = /\s* \s*/;
+// let input = document.createElement('input');
+// input.type = 'text';
+// document.body.append(input);
+// input.oninput = () => {
+//     let newStr = input.value.trim().split(re).join("|");
+// console.log(`/${newStr}/`);
+// }