Search code examples
node.jsgetstream-io

Stream.io: How to get a users unread messages count from the server


Is there any way to query a users total unread messages count across all channels from the server?

I can see it is possible to do this from the client using setUser but this is not appropriate for usage in a server side scenario. I am using nodejs, any suggestions would be appreciated.

Thanks, Mark


Solution

  • This is how I got all the messages across all channels from the server. I wrote it in JS, hopefully it will help you out:

    
    async function listUnreadMessages(user) {
      const serverClient = new StreamChat(api_key, stream_secret, options)
      await serverClient.setUser(
        {
          id: `${user.id}`,
          name: `${user.full_name}`,
          image: user.profile_image
        },
        user.chat_token
      )
    
      const filter = { members: { $in: [`${user.id}`] } }
      const sort = { last_message_at: -1 }
      const channels = await serverClient.queryChannels(filter, sort, {
        watch: true
      })
      let unreadList = {}
      const unreads = await Promise.all(
        channels.map((c) => {
          unreadList[c.id] = c.countUnread()
          return c.countUnread()
        })
      )
      serverClient.disconnect()
      return unreadList
    }