preface

This article describes how to quickly develop a chatroom application using vue. js and ChatKit. Chatkit provides a series of apis to make it easier to develop chat functions.

Example Create a Chatkit instance

So the first thing you need to do is create an instance of Chatkit, go to the Chatkit console and set it up, create a new room and a new user, and record the instanceLocator key that you’re going to use

Establish back-end services

Create a Node.js service to create users and provide JWT tokens, and install the yarn Add Express Cors Pusher-chatKit-server to start the service.

const cors = require('cors')
const express = require('express')
const Chatkit = require('pusher-chatkit-server')
const config = require('.. /config')

const app = express()
const PORT = config.SERVER_PORT || 4399

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// eslint-disable-next-line
const chatkit = new Chatkit.default({
  instanceLocator: config.CHATKIT_INSTANCELOCATOR,
  key: config.CHATKIT_KEY
})

app.post('/user', (req, res) => {
  const { username } = req.body

  const user = {
    id: username,
    name: username
  }

  chatkit
    .createUser(user)
    .then((a)= > res.status(201).json({ success: true.message: 'User created successfully', user }))
    .catch(error= > {
      res.status(error.status).json({ success: false.message: error.error_description })
    })
})

app.post('/auth', (req, res) => {
  const data = chatkit.authenticate({ userId: req.query.user_id })
  res.status(data.status).json(data.body)
})

app.listen(PORT, error => {
  if (error) {
    console.log(error)
  } else {
    console.log(`Server running on port ${PORT}`)}})Copy the code

New Front-end Project

Create a vue.js project and create a form to create a new user. Submit the form to the user route of the Express service you just created

<form class="create__form" @submit.prevent="createUser">
  <input 
    class="create__input" 
    v-model="newUserName" 
    placeholder="Enter your name" 
    autofocus 
    required
  />
</form>
Copy the code
async createUser() {
  const username = this.newUserName

  const result = await fetch(`${config.SERVER_HOST}:${config.SERVER_PORT}/user`, {
    method: 'POST'.headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username })
  })
  .then(res= > res.json())
  .catch(error= > error)

  if (result.success) {
    const user = result.user
    this.initChatApp(user.name) // The user is created successfully
  } else {
    console.log(result)
  }
}
Copy the code

After creating a user, initialize the application

async initChatApp(userId) {
  const chatManager = new Chatkit.ChatManager({
    userId,                                           // User name
    instanceLocator: config.CHATKIT_INSTANCELOCATOR,  // instanceLocator
    tokenProvider: new Chatkit.TokenProvider({       
      url: `${config.SERVER_HOST}:${config.SERVER_PORT}/auth`})})const currentUser = await chatManager.connect()

  const currentRoom = await currentUser
    .joinRoom({
      roomId: config.CHATKIT_ROOM_ID
    })
    .catch(error= > {
      return error
    })
    
  currentUser.subscribeToRoom({
    messageLimit: 20.roomId: config.CHATKIT_ROOM_ID, // The room ID created on the console
    hooks: {
      onNewMessage: message= > {
        this.users = this.users.map(user= > {
              if (user.name === message.senderId) {
                user.online = true
              }
              return user
            })
            this.messages.push(message)
          }
        }
    })

  const messages = await currentUser
    .fetchMessages({
      roomId: config.CHATKIT_ROOM_ID,
      direction: 'older'.limit: 20
    })
    .catch(error= > {
        console.error(error)
    })

  this.currentUser = currentUser
  this.currentRoom = currentRoom
  this.users = currentRoom.userIds.filter(name= >name ! == currentUser.name).map(name= > {
    return { name, online: false}})this.messages = messages
}
Copy the code

The page layout

Make layout and UI, use Grid for quick layout, build user list, message list and send message form

<ul class="chat__users">
  <li class="user-item" v-for="user of users" :key="user.id">
   <span class="name">{{ user.name }}</span>
   <span class="spot" :class="{ 'spot--online': user.online }"></span>
  </li>
</ul>
Copy the code
<ul class="chat__messages">
  <message-item 
    v-for="(message, index) of messages" 
    :key="index" 
    :message="message" 
    :currentUser="currentUser" 
   />
</ul>
Copy the code
<form class="chat__send" @submit.prevent="sendMessage">
  <input 
    class="input" 
    type="text" 
    @change="typingMessage" 
    v-model="newMessage" 
    autofocus 
    required 
    placeholder="Say something..." 
  />
  <button class="button" type="submit">send</button>
</form>
Copy the code
.chat {
  display: grid;
  grid-auto-columns: 240px auto;
  grid-auto-rows: 30px auto 70px;
  grid-template-areas:
    'users messages'
    'users messages'
    'users send';
  height: 100vh;
}  
Copy the code

Send a message

Use the API provided by ChatKit

sendMessage() {
  this.currentUser // Current user
    .sendMessage({
      text: this.newMessage, // Message content
      roomId: config.CHATKIT_ROOM_ID / / the room ID
    })
    .then(messageId= > {
      this.newMessage = ' '
    })
    .catch(error= > {
      this.newMessage = ' '
       console.log(error)
    })
}
Copy the code

The last

After the development, use yarn Build command to package the Vue project, and then use express built-in static middleware to mount the packaged dist directory. Open the port running Express in the browser to see the effect. This article only briefly describes how to develop. See github source code for specific implementation.

app.use('/', express.static(path.join(__dirname, '/dist')))
Copy the code

reference

vue-chat

CHATKIT DOCS

Build a Slack Clone with React and Pusher Chatkit