Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Build an instant messaging application to implement the Conversation page

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Building an instant messaging application implementation Conversation page". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "Building an instant messaging application implementation Conversation page".

Chat title

Let's start by creating the static/pages/conversation-page.js file, which contains the following:

Import http from'.. / http.js' import {navigate} from'.. / router.js' import {avatar, escapeHTML} from'.. / shared.js' export default async function conversationPage (conversationID) {let conversation try {conversation = await getConversation (conversationID)} catch (err) {alert (err.message) navigate ('/') True) return} const template = document.createElement ('template') template [XSS _ clean] = `conversation.otherParticipant.username Back ${avatar (conversation.otherParticipant)} ${conversation.otherParticipant.username} `const page = template.content return page} function getConversation (id) {return http.get ('/ api/conversations/' + id)}

This page receives the session ID extracted by the route from URL.

First, it makes an GET request to / api/ conversations/ {conversationID} to get information about the conversation. If an error occurs, we will display it and redirect it back to /. Then we present information about other participants.

Conversation list

We also get the latest news and display them.

Let conversation, messages try {[conversation, messages] = await Promise.all ([getConversation (conversationID), getMessages (conversationID),])}

Update the conversationPage () function to get the message. We use Promise.all () to execute both requests.

Function getMessages (conversationID) {return http.get (`/ api/conversations/$ {conversationID} / messages`)}

Initiate a GET request for / api/conversations/ {conversationID} / messages to get the latest news in the conversation.

Now, add the list to the tag.

Const messagesOList = page.getElementById ('messages') for (const message of messages.reverse ()) {messagesOList.appendChild (renderMessage (message))}

So we can attach the message to the list. We show them in reverse chronological order.

Function renderMessage (message) {const messageContent = escapeHTML (message.content) const messageDate = new Date (message.createdAt). ToLocaleString () const li = document.createElement ('li') if (message.mine) {li.classList.add (' owned')} Li [XSS _ clean] = `

${messageContent}

${messageDate} `return li}

Each message entry displays the message content itself and its timestamp. Using .mine, we can attach different css classes to the entry so that you can display the message on the right.

Message form

Send

Add the form to the current tag.

Page.getElementById ('message-form'). Onsubmit = messageSubmitter (conversationID)

Attach an event listener to the submit event.

Function messageSubmitter (conversationID) {return async ev = > {ev.preventDefault () const form = ev.currentTarget const input = form.querySelector ('input') const submitButton = form.querySelector (' button') input.disabled = true submitButton.disabled = true try {const message = await createMessage (input.value) ConversationID) input.value =''const messagesOList = document.getElementById (' messages') if (messagesOList = null) {return} messagesOList.appendChild (renderMessage (message))} catch (err) {if (err.statusCode = 422) {input.setCustomValidity (err.body) .errors.content)} else {alert (err.message)}} finally {input.disabled = false submitButton.disabled = false setTimeout (() = > {input.focus ()} 0)} function createMessage (content, conversationID) {return http.post (`/ api/conversations/$ {conversationID} / messages`, {content})}

We use partial application to get the conversation ID in the "submit" event handler. It takes the message content from the input and uses it to make a POST request to / api/conversations/ {conversationID} / messages. Then add the newly created message to the list.

Message subscription

To achieve real-time, we will also subscribe to the message flow on this page.

Page.addEventListener ('disconnect', subscribeToMessages (messageArriver (conversationID)

Add this line to the conversationPage () function.

Function subscribeToMessages (cb) {return http.subscribe ('/ api/messages') Cb)} function messageArriver (conversationID) {return message = > {if (message.conversationID! = = conversationID) {return} const messagesOList = document.getElementById ('messages') if (messagesOList = null) {return} messagesOList.appendChild (renderMessage (message) readMessages (message.conversationID)} function readMessages (conversationID) ) {return http.post (`/ api/conversations/$ {conversationID} / read_ messages`)}

Here we still use the part of the application to get the session ID. When the new message arrives, we first check to see if it comes from this conversation. If so, we pre-add the message entry to the list and POST a request to / api/conversations/ {conversationID} / read_messages to update when the participant last read the message.

Thank you for reading, the above is the content of "Building an instant messaging application to achieve Conversation page". After the study of this article, I believe you have a deeper understanding of the problem of building an instant messaging application to implement the Conversation page, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report