Ivar преди 2 години
родител
ревизия
b24cf6c470
променени са 6 файла, в които са добавени 108 реда и са изтрити 97 реда
  1. 23 44
      js/14_async-await/gq req/app.js
  2. 1 1
      js/14_async-await/gq req/index.html
  3. 43 28
      js/14_async-await/tasks/index.js
  4. 0 24
      js/15/index.js
  5. 0 0
      js/15_graph-ql/index.html
  6. 41 0
      js/15_graph-ql/index.js

+ 23 - 44
js/14_async-await/gq req/app.js

@@ -27,12 +27,13 @@ function gqReq1() {
       }
    }`, {q: "[{}]"}); //должно приехать { data: {CategoryFind: [........]}}
    let result = await response.json();
+   console.log(result)
    })()
 }
 
 
 
-// gqReq2()
+gqReq2()
 function gqReq2() {
 
    const getGQL = (url) =>
@@ -46,60 +47,38 @@ function gqReq2() {
          body: JSON.stringify({query, variables})
          //body с ключами query и variables
          
-      }).then(res => res.json()).then(data => {
-         // console.log(data)
+      }).then(res => res.json()).then((data) => {
+         // console.log(data)         
+         if ('errors' in data) {
+            Promise.reject(new Error('ОШИБКА'))
+            // throw new Error('GFSFSDFS')
+         } else {
+            return data.data
+         }
          //расковырять data, если все ок - отдать data.login или data.CategoryFindOne, или шо там еще
          //если есть errors, то выбросить исключение и тем самым зареджектить промис
-         return data
       });
 
 
    (async function() {
       const gql = getGQL('http://shop-roles.asmer.fs.a-level.com.ua/graphql')
+
+      console.log((await gql(`query cats($q:String) {
+         CategoryFind(query:$q){
+            name goods{
+               name images{
+               url
+               }
+            }
+         }
+      }`, {q: "[{}]"})))
+
       console.log((await gql(`
          query NameForMe1($login:String, $password:String){
             login(login:$login, password:$password)
          }
-      `, {login: 'tst', password: '123'})).data.login)
+      `, {login: 'tst', password: '123'})))
+
    })()
 }
 
-// const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTQ1NzZ9.Pi1GO6x7wdNrIrUKCQT-32-SsqmgFY-oFDrrXmw74-8'
-// JSON.parse(atob(token.split('.')[1]))
-
-
-// let qqq = 'fdhfakfalfjskgfsdadasdasdasdasdadfsdfkarieqfowerdaesfa'
-
-// function checkSum(str) {
-//    let res = 0
-//    for (let letter of str) {
-//       res += letter.charCodeAt()
-//    }
-//    return res
-// }
-// console.log(checkSum(qqq))
-
-// function sign(data, salt) {
-//    const json = JSON.stringify(data)
-//    const sum = checkSum(json + salt)
-//    return json + sum
-// }
-
-// function verify(signed, salt) {
-//    const json = signed.slice(0, signed.lastIndexOf('}') + 1)
-//    const tokenSum = + signed.slice(signed.lastIndexOf('}') + 1)
-//    const sum = checkSum(json + salt)
-
-//    console.log(json, tokenSum, sum)
-//    return sum === tokenSum
-// }
-
-
-
-
-localStorage.authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTk4NDl9.wzpQZ3KjywbNSfCt0Z_dua2AIrADL-ID-4Rs2cVnq0Q" 
-const originalFetch = fetch;
-fetch = (url, params={headers:{}}) => { 
-    params.headers.Authorization = "Bearer " + localStorage.authToken
-    return originalFetch(url, params)
-}

+ 1 - 1
js/14_async-await/gq req/index.html

@@ -4,7 +4,7 @@
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>promise</title>
+    <title>gql</title>
 </head>
     <body>
 

+ 43 - 28
js/14_async-await/tasks/index.js

@@ -72,7 +72,7 @@ function domEventPromiseWrapp() {
 
 
 
-pedestrianTrafficLightWrapp()
+// pedestrianTrafficLightWrapp()
 function pedestrianTrafficLightWrapp() {
 
    const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
@@ -133,42 +133,36 @@ function pedestrianTrafficLightWrapp() {
 
 
 
-// speedTestWrapp()
+speedTestWrapp()
 function speedTestWrapp() {
-   
-
-   const gql = (url, query, variables) => fetch(url, {
-      method: 'POST',   
-      headers: {'content-type': 'application/json'}, 
-      body: JSON.stringify({query, variables}),
-   });
-
-   (async function() {
-      let response = await gql("http://shop-roles.asmer.fs.a-level.com.ua/graphql", `query cats($q:String) {
-         CategoryFind(query:$q){
-            name goods{
-               name images{
-               url
-               }
-            }
+ 
+   async function speedtest(getPromise, count, parallel=1) {
+
+      let firstTime = performance.now()
+      for (let i = count; i > 0; i--) {
+         let promiseArr = []
+         for (let j = parallel; j > 0; j--) {           
+            promiseArr.push(getPromise())
          }
-      }`, {q: "[{}]"});
-      let result = await response.json();
-   })()
-
-
-
-   async function speedtest(getPromise, count,parallel=1){
-
+         // console.log(promiseArr)
+         await Promise.all(promiseArr)
+      }
+      let duration = performance.now() - firstTime
+      let parallelDuration = duration / (parallel*count) 
+      let parallelSpeed = (parallel*count) / duration
+      let queryDuration = duration / count
+      let querySpeed = 1 / queryDuration
 
       return {
               duration,
               querySpeed, //средняя скорость одного запроса
-              queryDuration, //
+              queryDuration, 
               parallelSpeed,
               parallelDuration
           }
       }
+
+      const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
       
       speedtest(() => delay(1000), 10, 10 ).then(result => console.log(result))
       // {duration: 10000, 
@@ -176,8 +170,29 @@ function speedTestWrapp() {
       // queryDuration: 1000, //1000 миллисекунд на один реальный запрос в среднем 
       // parallelSpeed: 0.01  // 100 запросов за 10000 миллисекунд
       // parallelDuration: 100 // 100 запросов за 10000 миллисекунд
-      speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 10, 5)
 
+      speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 10, 5).then(result => console.log(result))
+
+
+      const gql = (url, query, variables) => fetch(url, {
+         method: 'POST',   
+         headers: {'Content-Type': 'application/json'}, 
+         body: JSON.stringify({query, variables}),
+      })
+      .then(response => response.json())
+
+      speedtest(() => {
+                        gql("http://shop-roles.asmer.fs.a-level.com.ua/graphql", `query cats($q:String) {
+                           CategoryFind(query:$q){
+                              name goods{
+                                 name images{
+                                 url
+                                 }
+                              }
+                           }
+                        }`, {q: "[{}]"})
+                     }, 
+                     10, 100 ).then(result => console.log(result))
 }
 
 

+ 0 - 24
js/15/index.js

@@ -1,24 +0,0 @@
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}
-
-htmlTree()
-function htmlTree() {
-
-}

js/15/index.html → js/15_graph-ql/index.html


+ 41 - 0
js/15_graph-ql/index.js

@@ -0,0 +1,41 @@
+
+
+// const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTQ1NzZ9.Pi1GO6x7wdNrIrUKCQT-32-SsqmgFY-oFDrrXmw74-8'
+// JSON.parse(atob(token.split('.')[1]))
+
+
+// let qqq = 'fdhfakfalfjskgfsdadasdasdasdasdadfsdfkarieqfowerdaesfa'
+
+// function checkSum(str) {
+//    let res = 0
+//    for (let letter of str) {
+//       res += letter.charCodeAt()
+//    }
+//    return res
+// }
+// console.log(checkSum(qqq))
+
+// function sign(data, salt) {
+//    const json = JSON.stringify(data)
+//    const sum = checkSum(json + salt)
+//    return json + sum
+// }
+
+// function verify(signed, salt) {
+//    const json = signed.slice(0, signed.lastIndexOf('}') + 1)
+//    const tokenSum = + signed.slice(signed.lastIndexOf('}') + 1)
+//    const sum = checkSum(json + salt)
+
+//    console.log(json, tokenSum, sum)
+//    return sum === tokenSum
+// }
+
+
+
+
+localStorage.authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJsb2dpbiI6ImVxd2VxZXdldyIsImFjbCI6WyI2MWE0ZGIyOWM3NTBjMTJiYTZiYTQwMjIiLCJ1c2VyIl19LCJpYXQiOjE2MzgxOTk4NDl9.wzpQZ3KjywbNSfCt0Z_dua2AIrADL-ID-4Rs2cVnq0Q" 
+const originalFetch = fetch;
+fetch = (url, params={headers:{}}) => { 
+    params.headers.Authorization = "Bearer " + localStorage.authToken
+    return originalFetch(url, params)
+}