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).
This commit is contained in:
75
apps/api/src/modules/lists/events/route.ts
Normal file
75
apps/api/src/modules/lists/events/route.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
import { Hono } from 'hono'
|
||||
import { streamSSE } from 'hono/streaming'
|
||||
|
||||
import { requireSession } from '@/lib/auth-session'
|
||||
import { listEvents } from '@/lib/events'
|
||||
import { requireListMembership } from '@/lib/list-access'
|
||||
import { validate } from '@/lib/validate'
|
||||
import { ListParamsSchema } from '@/modules/lists/schema'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
/** Maximum silence between frames; a comment heartbeat is sent in between. */
|
||||
const HEARTBEAT_MS = 20_000
|
||||
|
||||
/**
|
||||
* GET /lists/:listId/events — Server-Sent Events stream with the changes
|
||||
* happening on a list (items, members, invitations). Members only.
|
||||
*
|
||||
* Events are buffered and written as they arrive; while the list is quiet a
|
||||
* comment heartbeat keeps the connection open through Bun's idle timeout and
|
||||
* any proxy in between.
|
||||
*/
|
||||
export const listEventsRoute = new Hono<AppEnv>().get(
|
||||
'/',
|
||||
requireSession,
|
||||
validate.param(ListParamsSchema),
|
||||
requireListMembership,
|
||||
(c) => {
|
||||
const { listId } = c.req.valid('param')
|
||||
|
||||
return streamSSE(c, async (stream) => {
|
||||
const pending: ListEvent[] = []
|
||||
|
||||
// Resolves a pending wait as soon as an event is buffered, so nothing has
|
||||
// to wait for the heartbeat interval.
|
||||
let wake: (() => void) | undefined
|
||||
const unsubscribe = listEvents.subscribe(listId, (event) => {
|
||||
pending.push(event)
|
||||
wake?.()
|
||||
})
|
||||
|
||||
stream.onAbort(() => unsubscribe())
|
||||
|
||||
const waitForEvent = () =>
|
||||
new Promise<void>((resolve) => {
|
||||
wake = resolve
|
||||
})
|
||||
|
||||
await stream.writeSSE({ event: 'ready', data: JSON.stringify({ listId }) })
|
||||
|
||||
while (!stream.aborted) {
|
||||
const event = pending.shift()
|
||||
|
||||
if (event) {
|
||||
await stream.writeSSE({ event: event.type, data: JSON.stringify(event) })
|
||||
continue
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
await Promise.race([
|
||||
waitForEvent(),
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, HEARTBEAT_MS)
|
||||
}),
|
||||
])
|
||||
clearTimeout(timer)
|
||||
wake = undefined
|
||||
|
||||
if (pending.length === 0 && !stream.aborted) {
|
||||
await stream.write(': ping\n\n')
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
@@ -3,6 +3,7 @@ import { Hono } from 'hono'
|
||||
import type { AppEnv } from '@/types'
|
||||
|
||||
import { createListRoute } from './create/route'
|
||||
import { listEventsRoute } from './events/route'
|
||||
import { getListRoute } from './get/route'
|
||||
import { listItemsModule } from './items'
|
||||
import { listListsRoute } from './list/route'
|
||||
@@ -17,3 +18,4 @@ export const listsModule = new Hono<AppEnv>()
|
||||
.route('/', updateListRoute)
|
||||
.route('/', setPrimaryListRoute)
|
||||
.route('/:listId/items', listItemsModule)
|
||||
.route('/:listId/events', listEventsRoute)
|
||||
|
||||
104
apps/api/src/modules/lists/items/create/use-case.test.ts
Normal file
104
apps/api/src/modules/lists/items/create/use-case.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { CreateItem } from './use-case'
|
||||
|
||||
type ItemRow = {
|
||||
id: string
|
||||
shoppingListId: string
|
||||
name: string
|
||||
completed: boolean
|
||||
boughtAt: Date | null
|
||||
quantity: string | null
|
||||
notes: string | null
|
||||
order: number
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
const now = new Date('2026-10-16T10:00:00.000Z')
|
||||
|
||||
function itemRow(input: {
|
||||
name: string
|
||||
quantity?: string | null
|
||||
notes?: string | null
|
||||
}): ItemRow {
|
||||
return {
|
||||
id: 'item-1',
|
||||
shoppingListId: 'list-1',
|
||||
name: input.name,
|
||||
completed: false,
|
||||
boughtAt: null,
|
||||
quantity: input.quantity ?? null,
|
||||
notes: input.notes ?? null,
|
||||
order: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}
|
||||
}
|
||||
|
||||
function createDb(options: { membership: unknown; item: ItemRow }) {
|
||||
const created: unknown[] = []
|
||||
|
||||
const db = {
|
||||
shoppingListMember: {
|
||||
findUnique: async () => options.membership,
|
||||
},
|
||||
listItem: {
|
||||
create: async (args: unknown) => {
|
||||
created.push(args)
|
||||
return options.item
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return { db: db as unknown as Database, created }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
describe('CreateItem', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, created } = createDb({ membership: null, item: itemRow({ name: 'Leche' }) })
|
||||
const { events, published } = createBus()
|
||||
const result = await new CreateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
name: 'Leche',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(created).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('creates the item and publishes item.created', async () => {
|
||||
const { db } = createDb({
|
||||
membership: { role: 'collaborator' },
|
||||
item: itemRow({ name: 'Leche', quantity: '1 L' }),
|
||||
})
|
||||
const { events, published } = createBus()
|
||||
const result = await new CreateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
userId: 'user-1',
|
||||
name: 'Leche',
|
||||
quantity: '1 L',
|
||||
})
|
||||
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||
expect(result.value.name).toBe('Leche')
|
||||
expect(published).toEqual([{ type: 'item.created', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
})
|
||||
@@ -7,13 +7,17 @@ import {
|
||||
type Result,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { toListItem } from '../serialize'
|
||||
|
||||
/** Adds an item to a shopping list. Only members can add items. */
|
||||
export class CreateItem {
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: {
|
||||
listId: string
|
||||
@@ -39,6 +43,9 @@ export class CreateItem {
|
||||
},
|
||||
})
|
||||
|
||||
return Ok(toListItem(item))
|
||||
const created = toListItem(item)
|
||||
this.events.publish({ type: 'item.created', listId: input.listId, item: created })
|
||||
|
||||
return Ok(created)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import type { ListEvent } from '@superlist/shared'
|
||||
|
||||
import { ListEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { UpdateItem } from './use-case'
|
||||
@@ -53,10 +55,19 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) {
|
||||
return { db: db as unknown as Database, updates }
|
||||
}
|
||||
|
||||
function createBus() {
|
||||
const events = new ListEvents()
|
||||
const published: ListEvent[] = []
|
||||
events.subscribe('list-1', (event) => published.push(event))
|
||||
|
||||
return { events, published }
|
||||
}
|
||||
|
||||
describe('UpdateItem', () => {
|
||||
it('answers 404 when the user does not belong to the list', async () => {
|
||||
const { db, updates } = createDb({ membership: null, item: itemRow(false, null) })
|
||||
const result = await new UpdateItem(db).execute({
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
@@ -67,11 +78,13 @@ describe('UpdateItem', () => {
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('answers 404 when the item does not belong to the list', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: null })
|
||||
const result = await new UpdateItem(db).execute({
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-of-another-list',
|
||||
userId: 'user-1',
|
||||
@@ -82,11 +95,13 @@ describe('UpdateItem', () => {
|
||||
if (result.ok) throw new Error('expected the use case to fail')
|
||||
expect(result.error.status).toBe(404)
|
||||
expect(updates).toHaveLength(0)
|
||||
expect(published).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('marks the item as bought and records boughtAt', async () => {
|
||||
it('marks the item as bought and publishes item.updated', async () => {
|
||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
|
||||
const result = await new UpdateItem(db).execute({
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
@@ -103,14 +118,17 @@ describe('UpdateItem', () => {
|
||||
|
||||
expect(result.value.completed).toBe(true)
|
||||
expect(result.value.boughtAt).toBe(data.data.boughtAt?.toISOString() ?? null)
|
||||
|
||||
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
|
||||
it('marks the item back to pending and clears boughtAt', async () => {
|
||||
it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => {
|
||||
const { db, updates } = createDb({
|
||||
membership: { role: 'collaborator' },
|
||||
item: itemRow(true, new Date('2026-10-15T12:00:00.000Z')),
|
||||
})
|
||||
const result = await new UpdateItem(db).execute({
|
||||
const { events, published } = createBus()
|
||||
const result = await new UpdateItem(db, events).execute({
|
||||
listId: 'list-1',
|
||||
itemId: 'item-1',
|
||||
userId: 'user-1',
|
||||
@@ -127,5 +145,7 @@ describe('UpdateItem', () => {
|
||||
|
||||
expect(result.value.completed).toBe(false)
|
||||
expect(result.value.boughtAt).toBeNull()
|
||||
|
||||
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type Result,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
import { toListItem } from '../serialize'
|
||||
@@ -17,7 +18,10 @@ import { toListItem } from '../serialize'
|
||||
* statistics, and is cleared when the item goes back to pending.
|
||||
*/
|
||||
export class UpdateItem {
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: {
|
||||
listId: string
|
||||
@@ -49,6 +53,9 @@ export class UpdateItem {
|
||||
},
|
||||
})
|
||||
|
||||
return Ok(toListItem(updated))
|
||||
const dto = toListItem(updated)
|
||||
this.events.publish({ type: 'item.updated', listId: input.listId, item: dto })
|
||||
|
||||
return Ok(dto)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,15 @@ import {
|
||||
type ShoppingListSummary,
|
||||
} from '@superlist/shared'
|
||||
|
||||
import { type ListEvents, listEvents } from '@/lib/events'
|
||||
import type { Database } from '@/lib/prisma'
|
||||
|
||||
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
||||
export class UpdateShoppingList {
|
||||
constructor(private readonly db: Database) {}
|
||||
constructor(
|
||||
private readonly db: Database,
|
||||
private readonly events: ListEvents = listEvents,
|
||||
) {}
|
||||
|
||||
async execute(input: {
|
||||
listId: string
|
||||
@@ -36,6 +40,8 @@ export class UpdateShoppingList {
|
||||
include: { _count: { select: { members: true } } },
|
||||
})
|
||||
|
||||
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
|
||||
|
||||
return Ok({
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
|
||||
Reference in New Issue
Block a user