12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- function jsonPost(url, data) {
- return new Promise((resolve, reject) => {
- const x = new XMLHttpRequest();
- x.onerror = () => reject(new Error('jsonPost failed'))
- //x.setRequestHeader('Content-Type', 'application/json');
- x.open("POST", url, true);
- x.send(JSON.stringify(data))
- x.onreadystatechange = () => {
- if (x.readyState === XMLHttpRequest.DONE && x.status === 200){
- resolve(JSON.parse(x.responseText))
- } else if (x.status !== 200){
- reject(new Error('status is not 200'))
- }
- }
- });
- }
- //Stage 0 && Stage 1
- const url = "http://students.a-level.com.ua:10012";
- let nextId = 0;
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms));
- const addZero = data => data < 10 ? `0${data}` : data;
- const buildDate = date => `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`;
- const buildMessage = (nick, message, time) => {
- return `<p>nick - ${nick}, message - ${message}, date - ${buildDate(new Date(time))}</p>`;
- }
- const sendMessage = async (nick, message) => {
- await jsonPost(url, {func: 'addMessage', nick: nick, message: message});
- }
- const getMessages = async () => {
- let messagesArray = await jsonPost(url, {func: 'getMessages', messageId: nextId});
- for (const message of messagesArray.data) {
- chatMessages.insertAdjacentHTML('afterbegin', buildMessage(message.nick, message.message, message.timestamp));
- }
- nextId = messagesArray.nextMessageId;
- }
- const sendAndCheck = async (nick, message) => {
- await Promise.all([sendMessage(nick, message), getMessages()]);
- }
- const checkLoop = async () => {
- while (true) {
- await Promise.all([delay(5000), getMessages()]);
- }
- }
- sendButton.addEventListener('click', () => {
- let nickValue = nickInput.value;
- let messageValue = messageInput.value;
- sendAndCheck(nickValue, messageValue);
- });
- checkLoop();
|