Files
superlist/apps/web/src/hooks/use-list-events.ts
Jose Selesan 4ed6432f60 feat: push live list changes over server-sent events
Every member viewing a list opens one SSE stream
(`GET /api/lists/:listId/events`) and refreshes the affected queries when
somebody else adds or buys an item, invites a person or renames the list, so
shared lists stay in sync without a reload.

- `@superlist/shared`: `ListEvent` / `ListEventType` contract.
- API: in-process `ListEvents` pub/sub keyed by list id; a `requireListMembership`
  middleware; a `streamSSE` route with a reconnect `ready` frame and a heartbeat,
  plus `server.timeout(req, 0)` so Bun does not close the quiet stream. Use cases
  publish `item.created`, `item.updated`, `list.updated`, `member.added` and
  `invitation.created` after their writes.
- Web: `useListEvents` subscribes with `EventSource` (`withCredentials`) and
  invalidates the matching TanStack Query keys, mounted where a list is shown and
  in the list settings page.

The API is reached through the same-origin `/api` prefix: every module is mounted
under `/api/*`, `apiBaseUrl` always appends `/api` to the optional `VITE_API_URL`,
the BetterAuth client points at the page origin, and Vite proxies `/api` to the
Bun API in dev (nginx does in production).
2026-10-16 14:58:31 -03:00

48 lines
1.5 KiB
TypeScript

import { useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react'
import { apiBaseUrl } from '@/lib/api-client'
import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events'
/**
* Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes
* the affected queries whenever another member adds or buys an item, invites
* somebody or renames the list — so the page updates without a reload.
*
* The session cookie is sent via `withCredentials`. `EventSource` reconnects on
* its own; a `ready` event is emitted on every (re)connection, used here to
* reconcile anything missed while disconnected.
*/
export function useListEvents(listId: string) {
const queryClient = useQueryClient()
useEffect(() => {
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
withCredentials: true,
})
const onReady = () => {
queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
}
source.addEventListener('ready', onReady)
const listeners = LIST_EVENT_TYPES.map((type) => {
const listener = () => {
for (const queryKey of queryKeysForListEvent(type, listId)) {
queryClient.invalidateQueries({ queryKey })
}
}
source.addEventListener(type, listener)
return { type, listener }
})
return () => {
source.removeEventListener('ready', onReady)
for (const { type, listener } of listeners) source.removeEventListener(type, listener)
source.close()
}
}, [listId, queryClient])
}