O

ouhammmourachid / realtime-chat

Public

Public and private chat rooms with realtime messages, attachments and edit tracking. Subscribe with the PocketBase SDK and messages arrive live.

  • Realtime
  • 0 deploys
  • 0 forks

Realtime Chat: rooms, members and messages

Public and private chat rooms with realtime messages, attachments and edit tracking. Subscribe with the PocketBase SDK and messages arrive live.

What you get

  • Public rooms anyone signed in can join; private rooms for members only
  • Realtime: pb.collection('messages').subscribe('*') respects the same access rules
  • Messages always sent as the signed-in user; only members can post in private rooms
  • Edited messages are flagged automatically
  • Up to 5 attachments per message
  • POST /api/rooms/{id}/join and /leave endpoints

Collections

rooms

FieldTypeNotes
name (required)text
descriptiontext
is_privateboolMembers only
owner (required)relation → usersSet by a hook to the signed-in user
membersrelation → users (many)The owner is always a member
ActionWho can do it
List / view@request.auth.id != '' && (is_private = false || members ?= @request.auth.id)
Createsigned-in users
Updateowner = @request.auth.id
Deleteowner = @request.auth.id

messages

FieldTypeNotes
room (required)relation → rooms
author (required)relation → usersSet by a hook to the signed-in user
texttext
attachmentsfileUp to 5 files, 10 MB each
editedboolSet by a hook
ActionWho can do it
List / view@request.auth.id != '' && (room.is_private = false || room.members ?= @request.auth.id)
Createsigned-in users
Updateauthor = @request.auth.id
Deleteauthor = @request.auth.id

Hooks

All hooks are in pb_hooks/main.pb.js and commented.

Quick start

import PocketBase from "pocketbase"
const pb = new PocketBase("https://YOUR-INSTANCE.pocketshub.com")

const room = await pb.collection("rooms").create({ name: "general" })

// Live messages for this room:
pb.collection("messages").subscribe("*", (e) => {
  if (e.record.room === room.id) console.log(e.action, e.record.text)
}, { expand: "author" })

await pb.collection("messages").create({ room: room.id, text: "Hello!" })

// History, newest first:
const history = await pb.collection("messages").getList(1, 50, {
  filter: `room = "${room.id}"`, sort: "-created", expand: "author",
})

Notes

  • Private rooms: the owner adds people by updating members (e.g. { "members+": userId }).

License

MIT

rooms
  • id
  • name
  • description
  • is_private
  • ownersingle
  • membersmultiple
  • created
  • updated
messages
  • id
  • roomsingle
  • authorsingle
  • text
  • attachmentsmultiple
  • edited
  • created
  • updated

2 collections, 1 relation. Hover a collection to trace its relations

main.pb.js110 lines
/// <reference path="../pb_data/types.d.ts" />

// ---------------------------------------------------------------------------
// Rooms
// ---------------------------------------------------------------------------

// The creator owns the room and is always a member.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to create rooms.")
    e.record.set("owner", e.auth.id)
  }
  e.record.set("members+", e.record.getString("owner"))
  e.next()
}, "rooms")

onRecordUpdateRequest((e) => {
  if (!e.hasSuperuserAuth() && e.record.original().getString("owner") !== e.record.getString("owner")) {
    throw new ForbiddenError("Room ownership can't be changed.")
  }
  e.next()
}, "rooms")

// POST /api/rooms/{id}/join  - join a public room.
routerAdd(
  "POST",
  "/api/rooms/{id}/join",
  (e) => {
    let room
    try {
      room = $app.findRecordById("rooms", e.request.pathValue("id"))
    } catch (_) {
      throw new NotFoundError("Room not found.")
    }
    if (room.getBool("is_private")) {
      throw new ForbiddenError("This room is private. Ask the owner to add you.")
    }
    room.set("members+", e.auth.id)
    $app.save(room)
    return e.json(200, { room: room.id })
  },
  $apis.requireAuth(),
)

// POST /api/rooms/{id}/leave
routerAdd(
  "POST",
  "/api/rooms/{id}/leave",
  (e) => {
    let room
    try {
      room = $app.findRecordById("rooms", e.request.pathValue("id"))
    } catch (_) {
      throw new NotFoundError("Room not found.")
    }
    if (room.getString("owner") === e.auth.id) {
      throw new BadRequestError("The owner can't leave their own room. Delete it instead.")
    }
    room.set("members-", e.auth.id)
    $app.save(room)
    return e.json(200, { room: room.id })
  },
  $apis.requireAuth(),
)

// ---------------------------------------------------------------------------
// Messages
// ---------------------------------------------------------------------------

// Messages are sent as the signed-in user, only into rooms they can post in.
onRecordCreateRequest((e) => {
  if (!e.hasSuperuserAuth()) {
    if (!e.auth) throw new UnauthorizedError("Sign in to send messages.")
    e.record.set("author", e.auth.id)

    let room
    try {
      room = e.app.findRecordById("rooms", e.record.getString("room"))
    } catch (_) {
      throw new BadRequestError("Room not found.")
    }
    if (room.getBool("is_private")) {
      const members = room.getStringSlice("members")
      let isMember = false
      for (let i = 0; i < members.length; i++) {
        if (members[i] === e.auth.id) isMember = true
      }
      if (!isMember) throw new ForbiddenError("You're not a member of this room.")
    }
  }
  e.record.set("edited", false)
  e.next()
}, "messages")

// Authors can edit the text of their messages. Room and author stay fixed.
onRecordUpdateRequest((e) => {
  const original = e.record.original()
  if (!e.hasSuperuserAuth()) {
    if (
      original.getString("room") !== e.record.getString("room") ||
      original.getString("author") !== e.record.getString("author")
    ) {
      throw new ForbiddenError("Only the text of a message can be edited.")
    }
  }
  if (original.getString("text") !== e.record.getString("text")) {
    e.record.set("edited", true)
  }
  e.next()
}, "messages")