Browse Source

HW<18>to be continued

Gennadysht 2 years ago
parent
commit
e3f5ac2b61

+ 17 - 13
js/18Rest_Graph/hw_18_03_speedtest.html

@@ -5,32 +5,35 @@
         const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
         let duration = 0;
         async function speedtestOne(getPromise) {
-                let startTime = new Date();
-                await getPromise();
-                let endTime = new Date();
-                return endTime - startTime;
-            }
+            let startTime = new Date();
+            await getPromise();
+            let endTime = new Date();
+            return endTime - startTime;
+        }
         async function speedtest(getPromise, count, parallel = 1) {
             const arr = [];
             let startTime = new Date();
             let execCount = 0;
+            let queryDuration = 0;
             while (execCount < count) {
                 for (i = 0; i < parallel; i++) {
                     execCount++;
                     if (execCount > count)
                         break;
-                    arr.push(new Promise(async () => await getPromise()));
-                    let y = 0;
+                    arr.push(new Promise(
+                        async resolveFunc => {
+                            let res = await speedtestOne(getPromise);
+                            resolveFunc(res);
+                        }));
                 }
                 let results = await Promise.all(arr);
-                let x = 0;
+                queryDuration = results.reduce((va, v) => va + v);
             }
             let endTimeParallel = new Date();
+            querySpeed = queryDuration / count;
             parallelDuration = endTimeParallel - startTime;
             parallelSpeed = parallelDuration / count;
             duration += parallelDuration;
-            querySpeed = 0;
-            queryDuration = 0;
             return {
                 duration,
                 querySpeed, //средняя скорость одного запроса
@@ -39,13 +42,14 @@
                 parallelDuration
             }
         }
-
-        speedtest(() => delay(10000), 10, 10).then(result => console.log(result))
+        speedtest(() => delay(1000), 10, 10)
+            .then(result => console.log(result))
         // {duration: 10000,
         // querySpeed: 0.001, //1 тысячная запроса за миллисекунду
         // 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))
     </script>
 </body>

+ 62 - 0
js/18Rest_Graph/hw_18_04_graph.html

@@ -0,0 +1,62 @@
+<header>GQL</header>
+
+<body>
+    <script>
+        function gql(url, query, vars) {
+            let fetchSettings =
+            {
+                method: "POST",
+                headers:
+                {
+                    "Content-Type": "application/json",
+                    "Accept": "application/json"
+                },
+                body: JSON.stringify(
+                    {
+                        query: query,
+                        variables: vars
+
+                    })
+            };
+            return fetch(url, fetchSettings).then(res => res.json());
+        }
+
+        /*
+        let query =
+            `
+                 query myGoodFind($where:String){
+                     GoodFind(query:$where){
+                         _id name
+                     }
+                 }
+             `;
+        let vars =
+        {
+            "where": '[{"name":"/alax/"}]'
+        };
+        gql("http://shop-roles.node.ed.asmer.org.ua/graphql", query, vars)
+            .then(res => console.log(JSON.stringify(res, null, 4)));
+        */
+        async function test() {
+            async function test1() {
+                const catQuery = `query cats($q: String){
+                                        CategoryFind(query: $q){
+                                            _id name
+                                        }
+                                    }`;
+                const cats = await gql("http://shop-roles.node.ed.asmer.org.ua/graphql", catQuery, { q: "[{}]" });
+                console.log(cats); //список категорий с _id name и всем таким прочим
+
+
+                const loginQuery = `query login($login:String, $password:String){
+                            	login(login:$login, password:$password)
+                        }`;
+
+                const token = await gql("http://shop-roles.node.ed.asmer.org.ua/graphql", loginQuery, { login: "test457", password: "123123" });
+                console.log(token);
+            }
+            await test1();
+        }
+        test();
+    </script>
+</body>

+ 33 - 0
js/18Rest_Graph/hw_18_05_jwt.html

@@ -0,0 +1,33 @@
+<header>jwt</header>
+
+<body>
+    <script>
+        function jwtDecode(token) {
+            if (!token || typeof token != "string")
+                return undefined;
+            let tokenArr = token.split(".");
+            if (tokenArr.length != 3)
+                return undefined;
+            try {
+                let tokenJsonStr = atob(tokenArr[1]);
+                let tokenJson = JSON.parse(tokenJsonStr);
+                return tokenJson;
+            }
+            catch {
+                return undefined;
+            }
+        }
+        const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MzIyMDVhZWI3NGUxZjVmMmVjMWEzMjAiLCJsb2dpbiI6InRlc3Q0NTciLCJhY2wiOlsiNjMyMjA1YWViNzRlMWY1ZjJlYzFhMzIwIiwidXNlciJdfSwiaWF0IjoxNjY4MjcyMTYzfQ.rxV1ki9G6LjT2IPWcqkMeTi_1K9sb3Si8vLB6UDAGdw"
+        console.log(jwtDecode(token))
+        try {
+            console.log(jwtDecode())         //undefined
+            console.log(jwtDecode("дичь"))   //undefined
+            console.log(jwtDecode("ey.ey.ey"))   //undefined
+
+            console.log('до сюда доработало, а значит jwtDecode не матерился в консоль красным цветом')
+        }
+        finally {
+            console.log('ДЗ, видимо, окончено')
+        }
+    </script>
+</body>