hm17.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // Chat =============================================================================================
  2. function jsonPost(url, data)
  3. {
  4. return new Promise((resolve, reject) => {
  5. var x = new XMLHttpRequest();
  6. x.onerror = () => reject(new Error('jsonPost failed'))
  7. //x.setRequestHeader('Content-Type', 'application/json');
  8. x.open("POST", url, true);
  9. x.send(JSON.stringify(data))
  10. x.onreadystatechange = () => {
  11. if (x.readyState == XMLHttpRequest.DONE && x.status == 200){
  12. resolve(JSON.parse(x.responseText))
  13. }
  14. else if (x.status != 200){
  15. reject(new Error('status is not 200'))
  16. }
  17. }
  18. })
  19. }
  20. function createMessanger (parent) {
  21. //stage 1 ============================================
  22. const fieldsContainer = document.createElement('div')
  23. parent.prepend(fieldsContainer)
  24. const nickField = document.createElement('input')
  25. fieldsContainer.append(nickField)
  26. nickField.placeholder = 'Your nick'
  27. const messageField = document.createElement('input')
  28. fieldsContainer.append(messageField)
  29. messageField.placeholder = 'Your message'
  30. const sendButton = document.createElement('button')
  31. fieldsContainer.append(sendButton)
  32. sendButton.innerText = 'SEND'
  33. const allMessages = document.createElement('span')
  34. fieldsContainer.append(allMessages)
  35. const messageCloud = document.createElement('div')
  36. parent.append(messageCloud)
  37. function sendMessage (nick, message) {
  38. jsonPost('http://students.a-level.com.ua:10012', {func: 'addMessage', nick: nick, message: message})
  39. .then(res => allMessages.innerText = `Всего сообщений: ${res.nextMessageId}`)
  40. }
  41. sendButton.addEventListener('click', () => {
  42. sendMessage(nickField.value, messageField.value)
  43. getMessages(id)
  44. })
  45. //stage 2 - 3 ================================================================================================
  46. let id = 0
  47. function getMessages () {
  48. jsonPost('http://students.a-level.com.ua:10012', {func: "getMessages", messageId: id})
  49. .then(res => {
  50. for (messageData of res.data) {
  51. const messageDataPlace = document.createElement('div')
  52. messageCloud.prepend(messageDataPlace)
  53. messageDataPlace.innerText = `${messageData.nick}: ${messageData.message}`
  54. const messageTime = document.createElement('span')
  55. messageDataPlace.append(messageTime)
  56. Object.assign(messageTime.style, {fontSize: '10px', color: 'grey', marginLeft: '5px'})
  57. messageTime.innerText = new Date(messageData.timestamp).toLocaleString()
  58. id = res.nextMessageId
  59. }
  60. })
  61. }
  62. getMessages()
  63. //stage 4 ================================================================================================
  64. setInterval(()=> getMessages(), 2000)
  65. }
  66. createMessanger(document.body)
  67. //stage 5-6 ================================================================================================
  68. async function jsonPost(url, data) {
  69. try {
  70. const res = await fetch(url, {method: 'POST', body: JSON.stringify(data)})
  71. const json = await res.json()
  72. return json
  73. }
  74. catch {
  75. alert('Error')
  76. }
  77. }
  78. function createMessanger (parent) {
  79. const fieldsContainer = document.createElement('div')
  80. parent.prepend(fieldsContainer)
  81. const nickField = document.createElement('input')
  82. fieldsContainer.append(nickField)
  83. nickField.placeholder = 'Your nick'
  84. const messageField = document.createElement('input')
  85. fieldsContainer.append(messageField)
  86. messageField.placeholder = 'Your message'
  87. const sendButton = document.createElement('button')
  88. fieldsContainer.append(sendButton)
  89. sendButton.innerText = 'SEND'
  90. const allMessages = document.createElement('span')
  91. fieldsContainer.append(allMessages)
  92. const messageCloud = document.createElement('div')
  93. parent.append(messageCloud)
  94. async function sendMessage (nick, message) {
  95. const res = await jsonPost('http://students.a-level.com.ua:10012', {func: 'addMessage', nick: nick, message: message})
  96. allMessages.innerText = `Всего сообщений: ${res.nextMessageId}`
  97. return res
  98. }
  99. let id = 0
  100. async function getMessages () {
  101. const res = await jsonPost('http://students.a-level.com.ua:10012', {func: "getMessages", messageId: id})
  102. for (messageData of res.data) {
  103. const messageDataPlace = document.createElement('div')
  104. messageCloud.prepend(messageDataPlace)
  105. messageDataPlace.innerText = `${messageData.nick}: ${messageData.message}`
  106. const messageTime = document.createElement('span')
  107. messageDataPlace.append(messageTime)
  108. Object.assign(messageTime.style, {fontSize: '10px', color: 'grey', marginLeft: '5px'})
  109. messageTime.innerText = new Date(messageData.timestamp).toLocaleString()
  110. id = res.nextMessageId
  111. }
  112. return res
  113. }
  114. async function sendAndCheck () {
  115. await sendMessage(nickField.value, messageField.value)
  116. await getMessages()
  117. }
  118. sendButton.addEventListener('click', sendAndCheck)
  119. async function delay (ms) {
  120. return await new Promise(resolve => setInterval(resolve,ms) )
  121. }
  122. async function checkLoop() {
  123. while (true) {
  124. await delay(2000)
  125. getMessages()
  126. }
  127. }
  128. checkLoop()
  129. getMessages()
  130. }
  131. createMessanger(document.body)
  132. // SWAPI Links =============================================================================================
  133. //Последовательные запросы =================================================================================
  134. async function swapiLinks(url) {
  135. const data = await fetch(url)
  136. const people = await data.json()
  137. for (let key in people) {
  138. if (people[key].includes('https://swapi.dev/api/')) {
  139. const link = await fetch(people[key])
  140. const dataFromLink = await link.json()
  141. people[key] = dataFromLink
  142. }
  143. else if (typeof people[key] === 'object') {
  144. for (let i = 0; i < people[key].length; i++) {
  145. if (typeof people[key][i] === 'string' && people[key][i].includes('https://swapi.dev/api/')) {
  146. const link = await fetch(people[key][i])
  147. const dataFromLink = await link.json()
  148. people[key][i] = dataFromLink
  149. }
  150. }
  151. }
  152. }
  153. return people
  154. }
  155. swapiLinks('https://swapi.dev/api/people/20')
  156. .then(yodaWithLinks => console.log(JSON.stringify(yodaWithLinks, null, 4)))
  157. //Параллельные запросы =================================================================================
  158. async function swapiLinks(url) {
  159. const swapiResp = await fetch(url)
  160. const swapiObj = await swapiResp.json()
  161. const linksArr = []
  162. for (let key in swapiObj) {
  163. if (typeof swapiObj[key] === 'string' && swapiObj[key].includes('https://swapi.dev/api/')) {
  164. linksArr.push(
  165. fetch(swapiObj[key])
  166. .then(res => res.json())
  167. .then(data => swapiObj[key] = data)
  168. )
  169. }
  170. if (typeof swapiObj[key] === 'object') {
  171. for (let i = 0; i < swapiObj[key].length; i++) {
  172. if (typeof swapiObj[key][i] === 'string' && swapiObj[key][i].includes('https://swapi.dev/api/')) {
  173. linksArr.push(
  174. fetch(swapiObj[key][i])
  175. .then(res => res.json())
  176. .then(data => swapiObj[key][i] = data)
  177. )
  178. }
  179. }
  180. }
  181. }
  182. await Promise.all(linksArr)
  183. return swapiObj
  184. }
  185. swapiLinks("https://swapi.dev/api/people/20/")
  186. .then(yodaWithLinks => console.log(JSON.stringify(yodaWithLinks, null, 4)))
  187. // domEventPromise =============================================================================================
  188. const knopka = document.createElement('button')
  189. document.body.appendChild(knopka)
  190. knopka.innerText = 'Knopka'
  191. function domEventPromise(element, eventName){
  192. function executor(resolve){
  193. const clickEvent = event => {
  194. resolve(event)
  195. element.removeEventListener(eventName, clickEvent)
  196. }
  197. element.addEventListener(eventName, clickEvent)
  198. }
  199. return new Promise(executor)
  200. }
  201. domEventPromise(knopka, 'click').then( e => console.log('event click happens', e))