index.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // ДЗ: Способы общения с серверами. REST, GraphQL и JWT.
  2. // задание 1 Светофор
  3. {
  4. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  5. async function trafficLight() {
  6. const greenLight = document.getElementById('green');
  7. const yellowLight = document.getElementById('yellow');
  8. const redLight = document.getElementById('red');
  9. while (true) {
  10. // включаем зеленый
  11. greenLight.style.backgroundColor = 'green';
  12. await delay(время_зеленого);
  13. // включаем желтый
  14. greenLight.style.backgroundColor = 'gray';
  15. yellowLight.style.backgroundColor = 'yellow';
  16. await delay(время_желтого);
  17. // включаем красный
  18. yellowLight.style.backgroundColor = 'gray';
  19. redLight.style.backgroundColor = 'red';
  20. await delay(время_красного);
  21. // выключаем красный
  22. redLight.style.backgroundColor = 'gray';
  23. }
  24. }
  25. }
  26. {
  27. // Stage 2
  28. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  29. async function trafficLight(greenLight, yellowLight, redLight, greenTime, yellowTime, redTime) {
  30. while (true) {
  31. // включаем зеленый
  32. greenLight.style.backgroundColor = 'green';
  33. await delay(greenTime);
  34. // включаем желтый
  35. greenLight.style.backgroundColor = 'gray';
  36. yellowLight.style.backgroundColor = 'yellow';
  37. await delay(yellowTime);
  38. // включаем красный
  39. yellowLight.style.backgroundColor = 'gray';
  40. redLight.style.backgroundColor = 'red';
  41. await delay(redTime);
  42. // выключаем красный
  43. redLight.style.backgroundColor = 'gray';
  44. }
  45. }
  46. // использование функции
  47. const greenLight = document.getElementById('green');
  48. const yellowLight = document.getElementById('yellow');
  49. const redLight = document.getElementById('red');
  50. trafficLight(greenLight, yellowLight, redLight, 2000, 1000, 3000);
  51. }
  52. // задание 2 PedestrianTrafficLight
  53. {
  54. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  55. async function pedestrianLight(greenLight, redLight, greenTime, redTime) {
  56. while (true) {
  57. // включаем зеленый
  58. greenLight.style.backgroundColor = 'green';
  59. await delay(greenTime);
  60. // включаем красный
  61. greenLight.style.backgroundColor = 'gray';
  62. redLight.style.backgroundColor = 'red';
  63. await delay(redTime);
  64. }
  65. }
  66. // использование функции
  67. const greenLight = document.getElementById('green');
  68. const redLight = document.getElementById('red');
  69. pedestrianLight(greenLight, redLight, 5000, 2000);
  70. }
  71. {
  72. // Stage 2
  73. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  74. function domEventPromise(element, event) {
  75. return new Promise((resolve) => {
  76. element.addEventListener(event, resolve, { once: true });
  77. });
  78. }
  79. async function pedestrianLight(greenLight, redLight, button, greenTime, redTime) {
  80. while (true) {
  81. // включаем зеленый
  82. greenLight.style.backgroundColor = 'green';
  83. redLight.style.backgroundColor = 'gray';
  84. // ожидаем событие кнопки или истечение времени
  85. await Promise.race([domEventPromise(button, 'click'), delay(greenTime)]);
  86. // включаем красный
  87. greenLight.style.backgroundColor = 'gray';
  88. redLight.style.backgroundColor = 'red';
  89. // ожидаем событие кнопки или истечение времени
  90. await Promise.race([domEventPromise(button, 'click'), delay(redTime)]);
  91. }
  92. }
  93. // использование функции
  94. const greenLight = document.getElementById('green');
  95. const redLight = document.getElementById('red');
  96. const button = document.getElementById('button');
  97. pedestrianLight(greenLight, redLight, button, 5000, 2000);
  98. }
  99. {
  100. // Stage 3
  101. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  102. function domEventPromise(element, event) {
  103. return new Promise((resolve) => {
  104. element.addEventListener(event, resolve, { once: true });
  105. });
  106. }
  107. async function pedestrianLight(greenLight, redLight, button, greenTime, redTime, buttonDelay) {
  108. while (true) {
  109. // включаем зеленый
  110. greenLight.style.backgroundColor = 'green';
  111. redLight.style.backgroundColor = 'gray';
  112. // ожидаем событие кнопки, истечение времени или задержку кнопки
  113. await Promise.race([
  114. domEventPromise(button, 'click').then(() => delay(buttonDelay)),
  115. delay(greenTime),
  116. ]);
  117. // включаем красный
  118. greenLight.style.backgroundColor = 'gray';
  119. redLight.style.backgroundColor = 'red';
  120. // ожидаем событие кнопки, истечение времени или задержку кнопки
  121. await Promise.race([
  122. domEventPromise(button, 'click').then(() => delay(buttonDelay)),
  123. delay(redTime),
  124. ]);
  125. }
  126. }
  127. }
  128. // задание 3 speedtest
  129. {
  130. async function speedtest(getPromise, count, parallel = 1) {
  131. let startTime = Date.now();
  132. let parallelDuration = 0;
  133. let queryDuration = 0;
  134. for (let i = 0; i < count; i++) {
  135. const promises = [];
  136. for (let j = 0; j < parallel; j++) {
  137. promises.push(getPromise());
  138. }
  139. const startParallelTime = Date.now();
  140. await Promise.all(promises);
  141. parallelDuration += Date.now() - startParallelTime;
  142. queryDuration += parallelDuration / parallel;
  143. }
  144. const duration = Date.now() - startTime;
  145. return {
  146. duration,
  147. querySpeed: queryDuration / count / 1000,
  148. queryDuration: queryDuration / count,
  149. parallelSpeed: parallelDuration / duration / 1000,
  150. parallelDuration: parallelDuration / count,
  151. };
  152. }
  153. // использование функции
  154. speedtest(() => delay(1000), 10, 10).then((result) => console.log(result));
  155. speedtest(() => fetch('http://swapi.dev/api/people/1').then((res) => res.json()), 10, 5).then(
  156. (result) => console.log(result),
  157. );
  158. }
  159. // задание 4 gql
  160. {
  161. async function gql(endpoint, query, variables) {
  162. try {
  163. const response = await fetch(endpoint, {
  164. method: 'POST',
  165. headers: {
  166. 'Content-Type': 'application/json',
  167. Accept: 'application/json',
  168. },
  169. body: JSON.stringify({
  170. query,
  171. variables,
  172. }),
  173. });
  174. return response.json();
  175. } catch (error) {
  176. console.error(error);
  177. return null;
  178. }
  179. }
  180. // использование функции
  181. (async () => {
  182. const catQuery = `query cats($q: String){
  183. CategoryFind(query: $q){
  184. _id name
  185. }
  186. }`;
  187. const cats = await gql('http://shop-roles.node.ed.asmer.org.ua/graphql', catQuery, {
  188. q: '[{}]',
  189. });
  190. console.log(cats); // список категорий с _id name и всем таким прочим
  191. const loginQuery = `query login($login:String, $password:String){
  192. login(login:$login, password:$password)
  193. }`;
  194. const token = await gql('http://shop-roles.node.ed.asmer.org.ua/graphql', loginQuery, {
  195. login: 'test457',
  196. password: '123123',
  197. });
  198. console.log(token);
  199. })();
  200. }
  201. // задание 5 jwtDecode
  202. {
  203. function jwtDecode(token) {
  204. if (!token) return;
  205. const [header, payload, signature] = token.split('.');
  206. if (!header || !payload || !signature) return;
  207. try {
  208. const decodedPayload = atob(payload);
  209. const data = JSON.parse(decodedPayload);
  210. return data;
  211. } catch {
  212. return;
  213. }
  214. }
  215. }
  216. {
  217. // использование:
  218. const token =
  219. 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOiI2MzIyMDVhZWI3NGUxZjVmMmVjMWEzMjAiLCJsb2dpbiI6InRlc3Q0NTciLCJhY2wiOlsiNjMyMjA1YWViNzRlMWY1ZjJlYzFhMzIwIiwidXNlciJdfSwiaWF0IjoxNjY4MjcyMTYzfQ.rxV1ki9G6LjT2IPWcqkMeTi_1K9sb3Si8vLB6UDAGdw';
  220. console.log(jwtDecode(token));
  221. // {
  222. // "sub": {
  223. // "id": "632205aeb74e1f5f2ec1a320",
  224. // "login": "test457",
  225. // "acl": [
  226. // "632205aeb74e1f5f2ec1a320",
  227. // "user"
  228. // ]
  229. // },
  230. // "iat": 1668272163
  231. // }
  232. try {
  233. console.log(jwtDecode()); // undefined
  234. console.log(jwtDecode('дичь')); // undefined
  235. console.log(jwtDecode('ey.ey.ey')); //undefined
  236. console.log('до сюда доработало, а значит jwtDecode не матерился в консоль красным цветом');
  237. } finally {
  238. console.log('ДЗ, видимо, окончено');
  239. }
  240. }