main.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. //Светофор
  2. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  3. const divLights = document.getElementById('divTraffic')
  4. const btn = document.getElementById('btn')
  5. async function trafficLight() {
  6. while (true) {
  7. // //включаем зеленый
  8. divLights.classList.remove('red')
  9. divLights.classList.add('green')
  10. await delay(3000)
  11. divLights.classList.remove('green')
  12. divLights.classList.add('yellow')
  13. await delay(1000)
  14. divLights.classList.remove('yellow')
  15. divLights.classList.add('red')
  16. await delay(3000)
  17. }
  18. }
  19. //trafficLight()
  20. //Stage 2
  21. async function trafficLightUniversal(divLights, greenRedTime = 3000, yellowTime = 1000) {
  22. while (true) {
  23. // //включаем зеленый
  24. divLights.classList.remove('red')
  25. divLights.classList.add('green')
  26. await delay(greenRedTime)
  27. divLights.classList.remove('green')
  28. divLights.classList.add('yellow')
  29. await delay(yellowTime)
  30. divLights.classList.remove('yellow')
  31. divLights.classList.add('red')
  32. await delay(greenRedTime)
  33. }
  34. }
  35. //trafficLight(divLights)
  36. async function domEventPromise(btn, eventName) {
  37. return new Promise((resolve) => {
  38. btn.addEventListener(eventName, (e) =>
  39. resolve(e)
  40. )
  41. btn.removeEventListener(eventName, (e) =>
  42. resolve(e))
  43. })
  44. }
  45. //domEventPromise(btn, 'click').then(e => console.log('event click happens', e))
  46. //domEventPromise(btn, 'mouseover').then(e => console.log('event mouseover happens', e))
  47. async function disabledBtn(btn, btnTime) {
  48. btn.disabled = true
  49. btn.classList.add('disabled')
  50. await delay(btnTime)
  51. btn.disabled = false
  52. btn.classList.remove('disabled')
  53. }
  54. async function PedestrianTrafficLight(divLights, greeTime = 5000, redTime = 45000, btnTime = 2000) {
  55. while (true) {
  56. divLights.classList.remove('red')
  57. divLights.classList.add('green')
  58. await Promise.race([delay(greeTime), domEventPromise((btn), 'click').then(e => {
  59. disabledBtn(e.target, btnTime)
  60. })])
  61. divLights.classList.remove('green')
  62. divLights.classList.add('red')
  63. await Promise.race([delay(redTime), domEventPromise((btn), 'click').then(e =>
  64. disabledBtn(e.target, btnTime)
  65. )])
  66. }
  67. }
  68. //PedestrianTrafficLight(divLights)
  69. //count - количество повторов
  70. //parallel - количество одновременных запросов/промисов в одном повторе
  71. //getPromise - функция, которая умеет вернуть нужный Вам промис для тестирования скорости его работы
  72. async function speedtest(getPromise, count, parallel = 1) {
  73. const start = new Date().getTime();
  74. try {
  75. let promiseArray = []
  76. for (let countPromise = 0; countPromise < count; countPromise++) {
  77. for (let paralelPromise = 0; paralelPromise < parallel; paralelPromise++) {
  78. promiseArray.push(getPromise())
  79. }
  80. console.log(promiseArray)
  81. await Promise.all(promiseArray)
  82. promiseArray.length = 0
  83. }
  84. } catch (error) {
  85. console.log(new Error(error))
  86. }
  87. const end = new Date().getTime();
  88. let durationTime = (end - start)
  89. let querySpeedTime = (count / durationTime)
  90. let queryDurationTime = (durationTime / count)
  91. let parallelSpeedTime = ((parallel * count) / durationTime)
  92. let parallelDurationTime = (durationTime / (parallel * count))
  93. return {
  94. duration: durationTime,
  95. querySpeed: querySpeedTime,
  96. queryDuration: queryDurationTime,
  97. parallelSpeed: parallelSpeedTime,
  98. parallelDuration: parallelDurationTime
  99. }
  100. }
  101. //speedtest(() => delay(1000), 10, 10).then(result => console.log(result))
  102. // {duration: 10000,
  103. // querySpeed: 0.001, //1 тысячная запроса за миллисекунду
  104. // queryDuration: 1000, //1000 миллисекунд на один реальный запрос в среднем
  105. // parallelSpeed: 0.01 // 100 запросов за 10000 миллисекунд
  106. // parallelDuration: 100 // 100 запросов за 10000 миллисекунд
  107. //speedtest(() => fetch('http://swapi.dev/api/people/1').then(res => res.json()), 10, 5)
  108. const getGQL = url =>
  109. (query, variables) => fetch(url, {
  110. //метод
  111. method: 'POST',
  112. headers: {
  113. //заголовок content-type
  114. "Content-Type": "application/json",
  115. ...(localStorage.authToken ? { "Authorization": "Bearer " + localStorage.authToken } : {})
  116. },
  117. body: JSON.stringify({ query, variables })
  118. //body с ключами query и variables
  119. }).then(res => res.json())
  120. .then(data => {
  121. if (data.data) {
  122. return Object.values(data.data)[0]
  123. } else throw new Error(JSON.stringify(data.errors))
  124. })
  125. //const gql = getGQL('http://shop-roles.asmer.fs.a-level.com.ua/graphql');
  126. const backendURL = 'http://shop-roles.asmer.fs.a-level.com.ua'
  127. const gql = getGQL(backendURL + '/graphql')
  128. //написать тестовых запросов:
  129. //логин
  130. async function queryLogin() {
  131. return await gql(` query login($login:String, $password:String){
  132. login(login:$login, password:$password)
  133. } `, { login: "LenaKyrylenko", password: "Litana13lank" }).then(res => console.log("login:", res))
  134. }
  135. queryLogin()
  136. //2 вариант
  137. async function gqlLogin(login, password) {
  138. return await gql(` query login($login:String, $password:String){
  139. login(login:$login, password:$password)
  140. } `, { login: login, password: password }).then(res => console.log("login:", res))
  141. }
  142. gqlLogin("LenaKyrylenko", "Litana13lank")
  143. //регистрация
  144. async function mutationrRegister() {
  145. return await gql(`mutation register($login: String, $password: String) {
  146. UserUpsert(user: {login: $login, password: $password, nick: $login}) {
  147. _id login
  148. }
  149. }`, { login: "Lena", password: "12345" }).then(res => console.log(res))
  150. }
  151. //mutationrRegister()
  152. //все категории
  153. async function queryAllCats() {
  154. return await gql(`query allCats {
  155. CategoryFind(query: "[{}]"){
  156. _id name goods { _id name description price images{url}}}
  157. }`).then(res => console.log("All categories:", res))
  158. }
  159. queryAllCats()
  160. //категория по id
  161. async function queryCatById(idCategory) {
  162. return await gql(`query catById($q: String){
  163. CategoryFindOne(query: $q){
  164. _id name goods {
  165. _id name price images {
  166. url
  167. }
  168. }
  169. }
  170. }`, { q: idCategory }).then(res => console.log("Category by id:", res))
  171. }
  172. let categoryId = "[{\"_id\": \"5dc458985df9d670df48cc47\"}]"
  173. queryCatById(categoryId)
  174. //товар по id
  175. async function queryGoodById(idGood) {
  176. return await gql(`query goodById($good: String){
  177. GoodFindOne(query: $good){
  178. _id name description price
  179. categories{_id name owner{_id login nick}}images{url}}
  180. }`, { good: idGood }).then(res => console.log("Good by id:", res))
  181. //.then(myToken => localStorage.authToken = myToken)
  182. }
  183. let goodId = "[{\"_id\": \"5e1f396856d8f720513e6cae\"}]"
  184. queryGoodById(goodId)
  185. //console.log("localStorage = ", localStorage)