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:
@@ -21,5 +21,7 @@ NODE_ENV="development"
|
|||||||
WEB_APP_URL="http://localhost:7153"
|
WEB_APP_URL="http://localhost:7153"
|
||||||
|
|
||||||
# --- apps/web ---
|
# --- apps/web ---
|
||||||
# Public URL of the API consumed by the frontend
|
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||||
VITE_API_URL="http://localhost:4100"
|
# you normally leave this unset. Only set it to point the frontend at a
|
||||||
|
# different API origin; the client always appends /api to it.
|
||||||
|
# VITE_API_URL=""
|
||||||
|
|||||||
@@ -39,12 +39,14 @@ export function createApp() {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
// BetterAuth owns every route under /api/auth/*.
|
// Every API route lives under /api: in production nginx serves the SPA on the
|
||||||
|
// root and proxies /api/* to this server, so unprefixed paths would collide
|
||||||
|
// with client routes (/lists, /invitations, ...). BetterAuth owns /api/auth/*.
|
||||||
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
|
app.on(['POST', 'GET'], '/api/auth/*', (c) => auth.handler(c.req.raw))
|
||||||
|
|
||||||
app.route('/health', healthModule)
|
app.route('/api/health', healthModule)
|
||||||
app.route('/lists', listsModule)
|
app.route('/api/lists', listsModule)
|
||||||
app.route('/invitations', invitationsModule)
|
app.route('/api/invitations', invitationsModule)
|
||||||
|
|
||||||
app.notFound(notFoundHandler)
|
app.notFound(notFoundHandler)
|
||||||
app.onError(errorHandler)
|
app.onError(errorHandler)
|
||||||
|
|||||||
@@ -9,5 +9,14 @@ logger.info({ port }, 'api listening')
|
|||||||
|
|
||||||
export default {
|
export default {
|
||||||
port,
|
port,
|
||||||
fetch: app.fetch,
|
fetch(req: Request, server: Bun.Server<unknown>) {
|
||||||
|
// SSE streams stay open while the list is quiet: without this, Bun closes
|
||||||
|
// the connection after its 10s idle timeout. Heartbeats are not enough on
|
||||||
|
// their own because they are sent less often than the default timeout.
|
||||||
|
if (new URL(req.url).pathname.endsWith('/events')) {
|
||||||
|
server.timeout(req, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
return app.fetch(req)
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
64
apps/api/src/lib/events.test.ts
Normal file
64
apps/api/src/lib/events.test.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import type { ListEvent, ListItem } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { ListEvents } from './events'
|
||||||
|
|
||||||
|
const item: ListItem = {
|
||||||
|
id: 'item-1',
|
||||||
|
listId: 'list-1',
|
||||||
|
name: 'Leche',
|
||||||
|
completed: false,
|
||||||
|
boughtAt: null,
|
||||||
|
quantity: null,
|
||||||
|
notes: null,
|
||||||
|
order: 0,
|
||||||
|
createdAt: '2026-10-16T10:00:00.000Z',
|
||||||
|
updatedAt: '2026-10-16T10:00:00.000Z',
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ListEvents', () => {
|
||||||
|
it('delivers an event to the subscribers of its list', () => {
|
||||||
|
const bus = new ListEvents()
|
||||||
|
const received: ListEvent[] = []
|
||||||
|
bus.subscribe('list-1', (event) => received.push(event))
|
||||||
|
|
||||||
|
const event: ListEvent = { type: 'item.created', listId: 'list-1', item }
|
||||||
|
bus.publish(event)
|
||||||
|
|
||||||
|
expect(received).toEqual([event])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not deliver to the subscribers of another list', () => {
|
||||||
|
const bus = new ListEvents()
|
||||||
|
const received: ListEvent[] = []
|
||||||
|
bus.subscribe('list-2', (event) => received.push(event))
|
||||||
|
|
||||||
|
bus.publish({ type: 'item.created', listId: 'list-1', item })
|
||||||
|
|
||||||
|
expect(received).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('delivers to every subscriber of the same list', () => {
|
||||||
|
const bus = new ListEvents()
|
||||||
|
const first: ListEvent[] = []
|
||||||
|
const second: ListEvent[] = []
|
||||||
|
bus.subscribe('list-1', (event) => first.push(event))
|
||||||
|
bus.subscribe('list-1', (event) => second.push(event))
|
||||||
|
|
||||||
|
bus.publish({ type: 'item.updated', listId: 'list-1', item })
|
||||||
|
|
||||||
|
expect(first).toHaveLength(1)
|
||||||
|
expect(second).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('stops delivering after unsubscribe', () => {
|
||||||
|
const bus = new ListEvents()
|
||||||
|
const received: ListEvent[] = []
|
||||||
|
const unsubscribe = bus.subscribe('list-1', (event) => received.push(event))
|
||||||
|
|
||||||
|
unsubscribe()
|
||||||
|
bus.publish({ type: 'item.created', listId: 'list-1', item })
|
||||||
|
|
||||||
|
expect(received).toHaveLength(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
38
apps/api/src/lib/events.ts
Normal file
38
apps/api/src/lib/events.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import type { ListEvent } from '@superlist/shared'
|
||||||
|
|
||||||
|
type ListEventListener = (event: ListEvent) => void
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-process pub/sub used to fan out list changes to the SSE streams of every
|
||||||
|
* member currently viewing a list.
|
||||||
|
*
|
||||||
|
* It only reaches the API instance that published the event, which is enough
|
||||||
|
* for a single-instance deployment. Scaling horizontally would need a shared
|
||||||
|
* bus (e.g. Postgres `LISTEN`/`NOTIFY`); this interface would stay the same.
|
||||||
|
*/
|
||||||
|
export class ListEvents {
|
||||||
|
private readonly listeners = new Map<string, Set<ListEventListener>>()
|
||||||
|
|
||||||
|
/** Subscribes to one list's events; returns the unsubscribe function. */
|
||||||
|
subscribe(listId: string, listener: ListEventListener): () => void {
|
||||||
|
const listeners = this.listeners.get(listId) ?? new Set<ListEventListener>()
|
||||||
|
listeners.add(listener)
|
||||||
|
this.listeners.set(listId, listeners)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
listeners.delete(listener)
|
||||||
|
if (listeners.size === 0) this.listeners.delete(listId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Delivers the event to every subscriber of its list. */
|
||||||
|
publish(event: ListEvent): void {
|
||||||
|
const listeners = this.listeners.get(event.listId)
|
||||||
|
if (!listeners) return
|
||||||
|
|
||||||
|
for (const listener of listeners) listener(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Process-wide bus shared by the use cases and the SSE routes. */
|
||||||
|
export const listEvents = new ListEvents()
|
||||||
27
apps/api/src/lib/list-access.ts
Normal file
27
apps/api/src/lib/list-access.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { problems } from '@superlist/shared'
|
||||||
|
import type { MiddlewareHandler } from 'hono'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { problemResponse } from '@/lib/problem-details'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guards a `/:listId/*` route so only members of the list reach it. Expects
|
||||||
|
* `requireSession` to have run first (it reads `c.get('user')`).
|
||||||
|
*/
|
||||||
|
export const requireListMembership: MiddlewareHandler<AppEnv> = async (c, next) => {
|
||||||
|
const listId = c.req.param('listId')
|
||||||
|
|
||||||
|
if (!listId) {
|
||||||
|
return problemResponse(c, problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const membership = await prisma.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId, userId: c.get('user').id } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return problemResponse(c, problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
await next()
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -12,6 +13,7 @@ import type { Database } from '@/lib/prisma'
|
|||||||
export async function acceptPendingInvitations(
|
export async function acceptPendingInvitations(
|
||||||
db: Database,
|
db: Database,
|
||||||
{ userId, email }: { userId: string; email: string },
|
{ userId, email }: { userId: string; email: string },
|
||||||
|
events: ListEvents = listEvents,
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
const pending = await db.shoppingListInvitation.findMany({
|
const pending = await db.shoppingListInvitation.findMany({
|
||||||
where: { email, status: 'pending', expiresAt: { gt: new Date() } },
|
where: { email, status: 'pending', expiresAt: { gt: new Date() } },
|
||||||
@@ -29,6 +31,8 @@ export async function acceptPendingInvitations(
|
|||||||
data: { status: 'accepted', acceptedAt: new Date() },
|
data: { status: 'accepted', acceptedAt: new Date() },
|
||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
|
|
||||||
|
events.publish({ type: 'member.added', listId: invitation.listId, userId })
|
||||||
}
|
}
|
||||||
|
|
||||||
return pending.length
|
return pending.length
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { describe, expect, it } from 'bun:test'
|
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 type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
import { AcceptInvitation } from './use-case'
|
import { AcceptInvitation } from './use-case'
|
||||||
@@ -46,6 +48,14 @@ function createDb({
|
|||||||
return { db: db as unknown as Database, updates, created }
|
return { db: db as unknown as Database, updates, created }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createBus() {
|
||||||
|
const events = new ListEvents()
|
||||||
|
const published: ListEvent[] = []
|
||||||
|
events.subscribe('list-1', (event) => published.push(event))
|
||||||
|
|
||||||
|
return { events, published }
|
||||||
|
}
|
||||||
|
|
||||||
describe('AcceptInvitation', () => {
|
describe('AcceptInvitation', () => {
|
||||||
it('answers 404 for an unknown token', async () => {
|
it('answers 404 for an unknown token', async () => {
|
||||||
const { db } = createDb({ invitation: undefined })
|
const { db } = createDb({ invitation: undefined })
|
||||||
@@ -79,7 +89,8 @@ describe('AcceptInvitation', () => {
|
|||||||
invitation: INVITATION,
|
invitation: INVITATION,
|
||||||
membership: { id: 'member-1' },
|
membership: { id: 'member-1' },
|
||||||
})
|
})
|
||||||
const result = await new AcceptInvitation(db, () => NOW).execute({
|
const { events, published } = createBus()
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW, events).execute({
|
||||||
token: INVITATION.id,
|
token: INVITATION.id,
|
||||||
userId: 'user-1',
|
userId: 'user-1',
|
||||||
email: 'beto@ejemplo.com',
|
email: 'beto@ejemplo.com',
|
||||||
@@ -89,6 +100,7 @@ describe('AcceptInvitation', () => {
|
|||||||
if (!result.ok) throw new Error('expected the use case to succeed')
|
if (!result.ok) throw new Error('expected the use case to succeed')
|
||||||
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
|
expect(result.value).toEqual({ listId: 'list-1', listName: 'Compra semanal' })
|
||||||
expect(updates).toHaveLength(0)
|
expect(updates).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('answers 400 and marks expired invitations', async () => {
|
it('answers 400 and marks expired invitations', async () => {
|
||||||
@@ -111,9 +123,10 @@ describe('AcceptInvitation', () => {
|
|||||||
expect(created).toHaveLength(0)
|
expect(created).toHaveLength(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('grants access and marks the invitation as accepted', async () => {
|
it('grants access, marks the invitation as accepted and publishes member.added', async () => {
|
||||||
const { db, updates, created } = createDb({ invitation: INVITATION })
|
const { db, updates, created } = createDb({ invitation: INVITATION })
|
||||||
const result = await new AcceptInvitation(db, () => NOW).execute({
|
const { events, published } = createBus()
|
||||||
|
const result = await new AcceptInvitation(db, () => NOW, events).execute({
|
||||||
token: INVITATION.id,
|
token: INVITATION.id,
|
||||||
userId: 'user-1',
|
userId: 'user-1',
|
||||||
// Compared in lower case, so the casing of the session email does not matter.
|
// Compared in lower case, so the casing of the session email does not matter.
|
||||||
@@ -129,5 +142,6 @@ describe('AcceptInvitation', () => {
|
|||||||
},
|
},
|
||||||
])
|
])
|
||||||
expect(updates).toHaveLength(1)
|
expect(updates).toHaveLength(1)
|
||||||
|
expect(published).toEqual([{ type: 'member.added', listId: 'list-1', userId: 'user-1' }])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
type Result,
|
type Result,
|
||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
/** Accepts an invitation for the signed-in user, matching it by token and email. */
|
/** Accepts an invitation for the signed-in user, matching it by token and email. */
|
||||||
@@ -14,6 +15,7 @@ export class AcceptInvitation {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly db: Database,
|
private readonly db: Database,
|
||||||
private readonly now: () => Date = () => new Date(),
|
private readonly now: () => Date = () => new Date(),
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async execute(input: {
|
async execute(input: {
|
||||||
@@ -66,6 +68,8 @@ export class AcceptInvitation {
|
|||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
|
|
||||||
|
this.events.publish({ type: 'member.added', listId: invitation.listId, userId: input.userId })
|
||||||
|
|
||||||
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
|
return Ok({ listId: invitation.list.id, listName: invitation.list.name })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
import { invitationEmail } from '@/lib/emails/invitation'
|
import { invitationEmail } from '@/lib/emails/invitation'
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import { logger } from '@/lib/logger'
|
import { logger } from '@/lib/logger'
|
||||||
import { type Email, sendEmail } from '@/lib/mailer'
|
import { type Email, sendEmail } from '@/lib/mailer'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
@@ -24,6 +25,7 @@ type CreateInvitationDependencies = {
|
|||||||
mailer?: Mailer
|
mailer?: Mailer
|
||||||
now?: () => Date
|
now?: () => Date
|
||||||
generateToken?: () => string
|
generateToken?: () => string
|
||||||
|
events?: ListEvents
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,6 +39,7 @@ export class CreateInvitation {
|
|||||||
private readonly mailer: Mailer
|
private readonly mailer: Mailer
|
||||||
private readonly now: () => Date
|
private readonly now: () => Date
|
||||||
private readonly generateToken: () => string
|
private readonly generateToken: () => string
|
||||||
|
private readonly events: ListEvents
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly db: Database,
|
private readonly db: Database,
|
||||||
@@ -45,6 +48,7 @@ export class CreateInvitation {
|
|||||||
this.mailer = dependencies.mailer ?? sendEmail
|
this.mailer = dependencies.mailer ?? sendEmail
|
||||||
this.now = dependencies.now ?? (() => new Date())
|
this.now = dependencies.now ?? (() => new Date())
|
||||||
this.generateToken = dependencies.generateToken ?? (() => randomUUID())
|
this.generateToken = dependencies.generateToken ?? (() => randomUUID())
|
||||||
|
this.events = dependencies.events ?? listEvents
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute(input: {
|
async execute(input: {
|
||||||
@@ -129,6 +133,8 @@ export class CreateInvitation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (invitedUser) {
|
if (invitedUser) {
|
||||||
|
this.events.publish({ type: 'member.added', listId: input.listId, userId: invitedUser.id })
|
||||||
|
|
||||||
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
// Best effort: the person already sees the list, so a mail failure is not fatal.
|
||||||
await this.mailer(message).catch((error: unknown) => {
|
await this.mailer(message).catch((error: unknown) => {
|
||||||
logger.warn({ err: error, to: email }, 'could not send the invitation email')
|
logger.warn({ err: error, to: email }, 'could not send the invitation email')
|
||||||
@@ -149,6 +155,8 @@ export class CreateInvitation {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.events.publish({ type: 'invitation.created', listId: input.listId, email })
|
||||||
|
|
||||||
return Ok({ status: 'invited', email })
|
return Ok({ status: 'invited', email })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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 type { AppEnv } from '@/types'
|
||||||
|
|
||||||
import { createListRoute } from './create/route'
|
import { createListRoute } from './create/route'
|
||||||
|
import { listEventsRoute } from './events/route'
|
||||||
import { getListRoute } from './get/route'
|
import { getListRoute } from './get/route'
|
||||||
import { listItemsModule } from './items'
|
import { listItemsModule } from './items'
|
||||||
import { listListsRoute } from './list/route'
|
import { listListsRoute } from './list/route'
|
||||||
@@ -17,3 +18,4 @@ export const listsModule = new Hono<AppEnv>()
|
|||||||
.route('/', updateListRoute)
|
.route('/', updateListRoute)
|
||||||
.route('/', setPrimaryListRoute)
|
.route('/', setPrimaryListRoute)
|
||||||
.route('/:listId/items', listItemsModule)
|
.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,
|
type Result,
|
||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
import { toListItem } from '../serialize'
|
import { toListItem } from '../serialize'
|
||||||
|
|
||||||
/** Adds an item to a shopping list. Only members can add items. */
|
/** Adds an item to a shopping list. Only members can add items. */
|
||||||
export class CreateItem {
|
export class CreateItem {
|
||||||
constructor(private readonly db: Database) {}
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
|
) {}
|
||||||
|
|
||||||
async execute(input: {
|
async execute(input: {
|
||||||
listId: string
|
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 { describe, expect, it } from 'bun:test'
|
||||||
|
import type { ListEvent } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { ListEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
import { UpdateItem } from './use-case'
|
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 }
|
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', () => {
|
describe('UpdateItem', () => {
|
||||||
it('answers 404 when the user does not belong to the list', async () => {
|
it('answers 404 when the user does not belong to the list', async () => {
|
||||||
const { db, updates } = createDb({ membership: null, item: itemRow(false, null) })
|
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',
|
listId: 'list-1',
|
||||||
itemId: 'item-1',
|
itemId: 'item-1',
|
||||||
userId: 'user-1',
|
userId: 'user-1',
|
||||||
@@ -67,11 +78,13 @@ describe('UpdateItem', () => {
|
|||||||
if (result.ok) throw new Error('expected the use case to fail')
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
expect(result.error.status).toBe(404)
|
expect(result.error.status).toBe(404)
|
||||||
expect(updates).toHaveLength(0)
|
expect(updates).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('answers 404 when the item does not belong to the list', async () => {
|
it('answers 404 when the item does not belong to the list', async () => {
|
||||||
const { db, updates } = createDb({ membership: { role: 'owner' }, item: null })
|
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',
|
listId: 'list-1',
|
||||||
itemId: 'item-of-another-list',
|
itemId: 'item-of-another-list',
|
||||||
userId: 'user-1',
|
userId: 'user-1',
|
||||||
@@ -82,11 +95,13 @@ describe('UpdateItem', () => {
|
|||||||
if (result.ok) throw new Error('expected the use case to fail')
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
expect(result.error.status).toBe(404)
|
expect(result.error.status).toBe(404)
|
||||||
expect(updates).toHaveLength(0)
|
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 { 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',
|
listId: 'list-1',
|
||||||
itemId: 'item-1',
|
itemId: 'item-1',
|
||||||
userId: 'user-1',
|
userId: 'user-1',
|
||||||
@@ -103,14 +118,17 @@ describe('UpdateItem', () => {
|
|||||||
|
|
||||||
expect(result.value.completed).toBe(true)
|
expect(result.value.completed).toBe(true)
|
||||||
expect(result.value.boughtAt).toBe(data.data.boughtAt?.toISOString() ?? null)
|
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({
|
const { db, updates } = createDb({
|
||||||
membership: { role: 'collaborator' },
|
membership: { role: 'collaborator' },
|
||||||
item: itemRow(true, new Date('2026-10-15T12:00:00.000Z')),
|
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',
|
listId: 'list-1',
|
||||||
itemId: 'item-1',
|
itemId: 'item-1',
|
||||||
userId: 'user-1',
|
userId: 'user-1',
|
||||||
@@ -127,5 +145,7 @@ describe('UpdateItem', () => {
|
|||||||
|
|
||||||
expect(result.value.completed).toBe(false)
|
expect(result.value.completed).toBe(false)
|
||||||
expect(result.value.boughtAt).toBeNull()
|
expect(result.value.boughtAt).toBeNull()
|
||||||
|
|
||||||
|
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
type Result,
|
type Result,
|
||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
import { toListItem } from '../serialize'
|
import { toListItem } from '../serialize'
|
||||||
@@ -17,7 +18,10 @@ import { toListItem } from '../serialize'
|
|||||||
* statistics, and is cleared when the item goes back to pending.
|
* statistics, and is cleared when the item goes back to pending.
|
||||||
*/
|
*/
|
||||||
export class UpdateItem {
|
export class UpdateItem {
|
||||||
constructor(private readonly db: Database) {}
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
|
) {}
|
||||||
|
|
||||||
async execute(input: {
|
async execute(input: {
|
||||||
listId: string
|
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,
|
type ShoppingListSummary,
|
||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
import type { Database } from '@/lib/prisma'
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
/** Renames a list. Only the owner (`role: owner`) may do it. */
|
||||||
export class UpdateShoppingList {
|
export class UpdateShoppingList {
|
||||||
constructor(private readonly db: Database) {}
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
|
) {}
|
||||||
|
|
||||||
async execute(input: {
|
async execute(input: {
|
||||||
listId: string
|
listId: string
|
||||||
@@ -36,6 +40,8 @@ export class UpdateShoppingList {
|
|||||||
include: { _count: { select: { members: true } } },
|
include: { _count: { select: { members: true } } },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
this.events.publish({ type: 'list.updated', listId: list.id, name: list.name })
|
||||||
|
|
||||||
return Ok({
|
return Ok({
|
||||||
id: list.id,
|
id: list.id,
|
||||||
name: list.name,
|
name: list.name,
|
||||||
|
|||||||
@@ -1 +1,4 @@
|
|||||||
VITE_API_URL="http://localhost:4100"
|
# Optional. Vite proxies /api/* to http://localhost:4100 in dev, so leave this
|
||||||
|
# unset unless the frontend must call the API on a different origin (the client
|
||||||
|
# always appends /api to it).
|
||||||
|
# VITE_API_URL=""
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { Card, CardContent } from '@/components/ui/card'
|
|||||||
import { Separator } from '@/components/ui/separator'
|
import { Separator } from '@/components/ui/separator'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { useItems, useUpdateItem } from '@/hooks/use-items'
|
import { useItems, useUpdateItem } from '@/hooks/use-items'
|
||||||
|
import { useListEvents } from '@/hooks/use-list-events'
|
||||||
import { useToday } from '@/hooks/use-today'
|
import { useToday } from '@/hooks/use-today'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
import { splitItems } from '@/lib/items'
|
import { splitItems } from '@/lib/items'
|
||||||
@@ -26,6 +27,9 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
const updateItem = useUpdateItem(listId)
|
const updateItem = useUpdateItem(listId)
|
||||||
const today = useToday()
|
const today = useToday()
|
||||||
|
|
||||||
|
// Live updates: another member adds or buys an item and this list refreshes.
|
||||||
|
useListEvents(listId)
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
|
|||||||
47
apps/web/src/hooks/use-list-events.ts
Normal file
47
apps/web/src/hooks/use-list-events.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
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])
|
||||||
|
}
|
||||||
@@ -1,6 +1,15 @@
|
|||||||
import { PROBLEM_CONTENT_TYPE, type ProblemDetails } from '@superlist/shared'
|
import { PROBLEM_CONTENT_TYPE, type ProblemDetails } from '@superlist/shared'
|
||||||
|
|
||||||
const baseUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:4100'
|
/**
|
||||||
|
* Base URL of the API. Also used to open the SSE streams (`list-events`).
|
||||||
|
*
|
||||||
|
* Empty by default: the API is reached through the `/api` prefix on the same
|
||||||
|
* origin (Vite proxies it in dev, nginx in production). Set `VITE_API_URL` to
|
||||||
|
* point at another origin — the `/api` suffix is always appended to it.
|
||||||
|
*/
|
||||||
|
const origin = import.meta.env.VITE_API_URL || ''
|
||||||
|
|
||||||
|
export const apiBaseUrl = `${origin}/api`
|
||||||
|
|
||||||
/** Error thrown when the API answers with a RFC 9457 Problem Details payload. */
|
/** Error thrown when the API answers with a RFC 9457 Problem Details payload. */
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
@@ -34,7 +43,7 @@ export async function readProblem(response: Response): Promise<ProblemDetails> {
|
|||||||
|
|
||||||
/** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */
|
/** Thin `fetch` wrapper: JSON by default, sessions enabled, problems as errors. */
|
||||||
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
|
export async function apiFetch<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||||
const response = await fetch(`${baseUrl}${path}`, {
|
const response = await fetch(`${apiBaseUrl}${path}`, {
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
...init,
|
...init,
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { createAuthClient } from 'better-auth/react'
|
import { createAuthClient } from 'better-auth/react'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* BetterAuth browser client. `baseURL` points at the Hono API, which mounts
|
* BetterAuth browser client. `baseURL` defaults to the page origin (the API is
|
||||||
* BetterAuth under `/api/auth/*`.
|
* proxied under `/api` in dev and production) and can be overridden with
|
||||||
|
* `VITE_API_URL`. BetterAuth appends `/api/auth` itself.
|
||||||
*/
|
*/
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: import.meta.env.VITE_API_URL ?? 'http://localhost:4100',
|
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const { signIn, signUp, signOut, useSession } = authClient
|
export const { signIn, signUp, signOut, useSession } = authClient
|
||||||
|
|||||||
16
apps/web/src/lib/list-events.test.ts
Normal file
16
apps/web/src/lib/list-events.test.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { queryKeysForListEvent } from './list-events'
|
||||||
|
|
||||||
|
describe('queryKeysForListEvent', () => {
|
||||||
|
it('refreshes only the item list for item events', () => {
|
||||||
|
expect(queryKeysForListEvent('item.created', 'list-1')).toEqual([['lists', 'list-1', 'items']])
|
||||||
|
expect(queryKeysForListEvent('item.updated', 'list-1')).toEqual([['lists', 'list-1', 'items']])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refreshes the list detail and the overview for membership and invitations', () => {
|
||||||
|
for (const type of ['invitation.created', 'member.added', 'list.updated'] as const) {
|
||||||
|
expect(queryKeysForListEvent(type, 'list-1')).toEqual([['lists', 'list-1'], ['lists']])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
28
apps/web/src/lib/list-events.ts
Normal file
28
apps/web/src/lib/list-events.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import type { ListEventType } from '@superlist/shared'
|
||||||
|
import type { QueryKey } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
/** Every event type the SSE stream can emit, in one place for the client. */
|
||||||
|
export const LIST_EVENT_TYPES: readonly ListEventType[] = [
|
||||||
|
'item.created',
|
||||||
|
'item.updated',
|
||||||
|
'invitation.created',
|
||||||
|
'member.added',
|
||||||
|
'list.updated',
|
||||||
|
]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query keys a list event invalidates. Item changes only touch the item list;
|
||||||
|
* membership and invitation changes refresh the list detail and the overview
|
||||||
|
* (whose summary carries `memberCount`).
|
||||||
|
*/
|
||||||
|
export function queryKeysForListEvent(type: ListEventType, listId: string): QueryKey[] {
|
||||||
|
switch (type) {
|
||||||
|
case 'item.created':
|
||||||
|
case 'item.updated':
|
||||||
|
return [['lists', listId, 'items']]
|
||||||
|
case 'invitation.created':
|
||||||
|
case 'member.added':
|
||||||
|
case 'list.updated':
|
||||||
|
return [['lists', listId], ['lists']]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import { Input } from '@/components/ui/input'
|
|||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { useCreateInvitation } from '@/hooks/use-invitations'
|
import { useCreateInvitation } from '@/hooks/use-invitations'
|
||||||
import { listQueryOptions, useList } from '@/hooks/use-list'
|
import { listQueryOptions, useList } from '@/hooks/use-list'
|
||||||
|
import { useListEvents } from '@/hooks/use-list-events'
|
||||||
import { useRenameList, useSetPrimaryList } from '@/hooks/use-lists'
|
import { useRenameList, useSetPrimaryList } from '@/hooks/use-lists'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
|
|
||||||
@@ -33,6 +34,9 @@ function ListSettingsPage() {
|
|||||||
const { listId } = Route.useParams()
|
const { listId } = Route.useParams()
|
||||||
const { data: list, isPending, error } = useList(listId)
|
const { data: list, isPending, error } = useList(listId)
|
||||||
|
|
||||||
|
// Live updates: refresh the members and invitations when they change elsewhere.
|
||||||
|
useListEvents(listId)
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-2xl">
|
<div className="mx-auto w-full max-w-2xl">
|
||||||
|
|||||||
@@ -21,5 +21,10 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
port: 7153,
|
port: 7153,
|
||||||
|
// Same-origin API in dev, mirroring nginx in production: the browser calls
|
||||||
|
// `/api/*` on the Vite server and it is forwarded to the Bun API.
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:4100',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
20
packages/shared/src/events.ts
Normal file
20
packages/shared/src/events.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import type { ListItem } from './shopping-list'
|
||||||
|
|
||||||
|
/** Discriminator of the events a list's SSE stream can emit. */
|
||||||
|
export type ListEventType =
|
||||||
|
| 'item.created'
|
||||||
|
| 'item.updated'
|
||||||
|
| 'invitation.created'
|
||||||
|
| 'member.added'
|
||||||
|
| 'list.updated'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Server-Sent Events pushed to the members viewing a list
|
||||||
|
* (`GET /lists/:listId/events`). `type` is the SSE `event:` name and the whole
|
||||||
|
* object is the JSON `data:` payload.
|
||||||
|
*/
|
||||||
|
export type ListEvent =
|
||||||
|
| { type: 'item.created' | 'item.updated'; listId: string; item: ListItem }
|
||||||
|
| { type: 'invitation.created'; listId: string; email: string }
|
||||||
|
| { type: 'member.added'; listId: string; userId: string }
|
||||||
|
| { type: 'list.updated'; listId: string; name: string }
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
export * from './events'
|
||||||
export * from './problem-details'
|
export * from './problem-details'
|
||||||
export * from './result'
|
export * from './result'
|
||||||
export * from './shopping-list'
|
export * from './shopping-list'
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
"build": {
|
"build": {
|
||||||
"dependsOn": ["^build"],
|
"dependsOn": ["^build"],
|
||||||
"inputs": ["$TURBO_DEFAULT$", ".env*"],
|
"inputs": ["$TURBO_DEFAULT$", ".env*"],
|
||||||
"outputs": ["dist/**"]
|
"outputs": ["dist/**"],
|
||||||
|
"env": ["VITE_API_URL"]
|
||||||
},
|
},
|
||||||
"lint": {},
|
"lint": {},
|
||||||
"typecheck": {},
|
"typecheck": {},
|
||||||
@@ -32,7 +33,8 @@
|
|||||||
"NODE_ENV",
|
"NODE_ENV",
|
||||||
"RESEND_API_KEY",
|
"RESEND_API_KEY",
|
||||||
"MAIL_FROM",
|
"MAIL_FROM",
|
||||||
"WEB_APP_URL"
|
"WEB_APP_URL",
|
||||||
|
"VITE_API_URL"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"db:generate": {
|
"db:generate": {
|
||||||
|
|||||||
Reference in New Issue
Block a user