misc rooms endpoints, friends

This commit is contained in:
Devin Zuczek
2026-07-08 13:22:06 -04:00
parent 390843c679
commit a1d9fc17f0
22 changed files with 823 additions and 123 deletions
+52 -31
View File
@@ -4,14 +4,16 @@
* generated (virtual) columns extracted from that JSON and indexed. This keeps
* the room shape flexible while still allowing fast lookups by id/name/creator.
*
* `SCHEMA_DDL` mirrors `migrations/0001_init.sql`; the room data is seeded from
* `static/ImportRooms.json` by `migrations/0002_import_rooms.sql`. Tests apply
* `SCHEMA_DDL` then seed the imported rooms directly.
* `SCHEMA_DDL` mirrors the head schema after all migrations (`0001_init.sql`
* created the table as `rooms`; `0005_rename_room.sql` renamed it to `room`);
* the room data is seeded from `static/ImportRooms.json` by
* `migrations/0002_import_rooms.sql`. Tests apply `SCHEMA_DDL` then seed the
* imported rooms directly.
*/
/** Schema DDL (mirror of migrations/0001_init.sql, sans the seed INSERT). */
/** Schema DDL (mirror of the head migration schema, sans the seed INSERT). */
export const SCHEMA_DDL: string[] = [
`CREATE TABLE IF NOT EXISTS rooms (
`CREATE TABLE IF NOT EXISTS room (
data TEXT NOT NULL,
room_id INTEGER GENERATED ALWAYS AS (json_extract(data, '$.RoomId')) VIRTUAL,
name TEXT GENERATED ALWAYS AS (json_extract(data, '$.Name')) VIRTUAL,
@@ -19,9 +21,9 @@ export const SCHEMA_DDL: string[] = [
creator_account_id INTEGER GENERATED ALWAYS AS (json_extract(data, '$.CreatorAccountId')) VIRTUAL,
is_dorm INTEGER GENERATED ALWAYS AS (json_extract(data, '$.IsDorm')) VIRTUAL
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_rooms_room_id ON rooms (room_id)`,
`CREATE INDEX IF NOT EXISTS idx_rooms_name_lower ON rooms (name_lower)`,
`CREATE INDEX IF NOT EXISTS idx_rooms_creator ON rooms (creator_account_id)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_rooms_room_id ON room (room_id)`,
`CREATE INDEX IF NOT EXISTS idx_rooms_name_lower ON room (name_lower)`,
`CREATE INDEX IF NOT EXISTS idx_rooms_creator ON room (creator_account_id)`,
// Per-player interaction state with a room (cheered/favorited + last visit).
// One row per (player, room); cheer/favorite are toggled in place.
`CREATE TABLE IF NOT EXISTS interaction (
@@ -65,7 +67,7 @@ export async function cloneRoom(
if (!source || source.CloningAllowed === false) return null
const row = await db
.prepare('SELECT MAX(room_id) AS maxId FROM rooms')
.prepare('SELECT MAX(room_id) AS maxId FROM room')
.first<{ maxId: number | null }>()
const newRoomId = (row?.maxId ?? 0) + 1
@@ -93,7 +95,7 @@ export async function cloneRoom(
CreatedAt: new Date().toISOString(),
}
await db.prepare('INSERT INTO rooms (data) VALUES (?1)').bind(JSON.stringify(cloned)).run()
await db.prepare('INSERT INTO room (data) VALUES (?1)').bind(JSON.stringify(cloned)).run()
return cloned
}
@@ -104,7 +106,7 @@ export async function setRoomDescription(
description: string
): Promise<void> {
await db
.prepare("UPDATE rooms SET data = json_set(data, '$.Description', ?2) WHERE room_id = ?1")
.prepare("UPDATE room SET data = json_set(data, '$.Description', ?2) WHERE room_id = ?1")
.bind(roomId, description)
.run()
}
@@ -112,7 +114,7 @@ export async function setRoomDescription(
/** Set a room's Name in place (the caller checks ownership + name uniqueness first). */
export async function setRoomName(db: D1Database, roomId: number, name: string): Promise<void> {
await db
.prepare("UPDATE rooms SET data = json_set(data, '$.Name', ?2) WHERE room_id = ?1")
.prepare("UPDATE room SET data = json_set(data, '$.Name', ?2) WHERE room_id = ?1")
.bind(roomId, name)
.run()
}
@@ -120,7 +122,7 @@ export async function setRoomName(db: D1Database, roomId: number, name: string):
/** Set a room's ImageName in place (the caller is responsible for the owner check). */
export async function setRoomImage(db: D1Database, roomId: number, imageName: string): Promise<void> {
await db
.prepare("UPDATE rooms SET data = json_set(data, '$.ImageName', ?2) WHERE room_id = ?1")
.prepare("UPDATE room SET data = json_set(data, '$.ImageName', ?2) WHERE room_id = ?1")
.bind(roomId, imageName)
.run()
}
@@ -130,19 +132,38 @@ export async function setRoomImage(db: D1Database, roomId: number, imageName: st
* (case-insensitive). The caller supplies the already-loaded room (owner-checked)
* to avoid a re-read; the whole room JSON is rewritten. Returns the updated room.
*/
export async function addRoomTag(
/**
* Mutually-exclusive "main" room tags. The UI presents these as radio buttons, so
* setting one clears any other main tag. Compared case-insensitively.
*/
const MAIN_TAGS = new Set(['pvp', 'quest', 'game', 'hangout', 'art'])
export async function toggleRoomTag(
db: D1Database,
roomId: number,
room: Room,
tag: string
): Promise<Room> {
const tags = Array.isArray(room.Tags) ? (room.Tags as Array<Record<string, unknown>>) : []
if (!tags.some((t) => String(t?.Tag).toLowerCase() === tag.toLowerCase())) {
tags.push({ Tag: tag, Type: 0 })
const lower = tag.toLowerCase()
const tagLower = (t: Record<string, unknown>): string => String(t?.Tag).toLowerCase()
const existing = tags.findIndex((t) => tagLower(t) === lower)
// The client has no delete/patch endpoint — the same call toggles a tag: remove
// it if already present, add it otherwise. Adding a main tag is a radio pick, so
// it also clears any other main tag already set.
let nextTags: Array<Record<string, unknown>>
if (existing !== -1) {
nextTags = tags.filter((_, i) => i !== existing)
} else if (MAIN_TAGS.has(lower)) {
nextTags = [...tags.filter((t) => !MAIN_TAGS.has(tagLower(t))), { Tag: tag, Type: 0 }]
} else {
nextTags = [...tags, { Tag: tag, Type: 0 }]
}
const updated: Room = { ...room, Tags: tags }
const updated: Room = { ...room, Tags: nextTags }
await db
.prepare('UPDATE rooms SET data = ?2 WHERE room_id = ?1')
.prepare('UPDATE room SET data = ?2 WHERE room_id = ?1')
.bind(roomId, JSON.stringify(updated))
.run()
return updated
@@ -201,7 +222,7 @@ export async function saveSubRoomData(
if (input.inventionUsage !== undefined) room.InventionUsage = input.inventionUsage
await db
.prepare('UPDATE rooms SET data = ?2 WHERE room_id = ?1')
.prepare('UPDATE room SET data = ?2 WHERE room_id = ?1')
.bind(roomId, JSON.stringify(room))
.run()
return room
@@ -217,7 +238,7 @@ const parseAll = (rows: RoomRow[]): Room[] => rows.map((r) => JSON.parse(r.data)
/** Look up a single room by its RoomId. */
export async function getRoomById(db: D1Database, roomId: number): Promise<Room | null> {
return parseOne(
await db.prepare('SELECT data FROM rooms WHERE room_id = ?1').bind(roomId).first<RoomRow>()
await db.prepare('SELECT data FROM room WHERE room_id = ?1').bind(roomId).first<RoomRow>()
)
}
@@ -225,7 +246,7 @@ export async function getRoomById(db: D1Database, roomId: number): Promise<Room
export async function getRoomByName(db: D1Database, name: string): Promise<Room | null> {
return parseOne(
await db
.prepare('SELECT data FROM rooms WHERE name_lower = ?1')
.prepare('SELECT data FROM room WHERE name_lower = ?1')
.bind(name.toLowerCase())
.first<RoomRow>()
)
@@ -236,7 +257,7 @@ export async function getRoomsByIds(db: D1Database, ids: number[]): Promise<Room
if (ids.length === 0) return []
const placeholders = ids.map((_, i) => `?${i + 1}`).join(',')
const { results } = await db
.prepare(`SELECT data FROM rooms WHERE room_id IN (${placeholders})`)
.prepare(`SELECT data FROM room WHERE room_id IN (${placeholders})`)
.bind(...ids)
.all<RoomRow>()
return parseAll(results)
@@ -245,7 +266,7 @@ export async function getRoomsByIds(db: D1Database, ids: number[]): Promise<Room
/** All rooms created by an account (e.g. their dorm). */
export async function getRoomsByCreator(db: D1Database, accountId: number): Promise<Room[]> {
const { results } = await db
.prepare('SELECT data FROM rooms WHERE creator_account_id = ?1')
.prepare('SELECT data FROM room WHERE creator_account_id = ?1')
.bind(accountId)
.all<RoomRow>()
return parseAll(results)
@@ -277,7 +298,7 @@ export async function getFavoritedRooms(
.prepare(
`SELECT r.data AS data
FROM interaction i
JOIN rooms r ON r.room_id = i.room_id
JOIN room r ON r.room_id = i.room_id
WHERE i.player_id = ?1 AND i.favorited = 1
ORDER BY i.last_visited_at DESC`
)
@@ -302,7 +323,7 @@ export async function getVisitedRooms(
.prepare(
`SELECT r.data AS data
FROM interaction i
JOIN rooms r ON r.room_id = i.room_id
JOIN room r ON r.room_id = i.room_id
WHERE i.player_id = ?1 AND i.last_visited_at IS NOT NULL
ORDER BY i.last_visited_at DESC`
)
@@ -459,7 +480,7 @@ export async function searchRooms(
if (q === '') return { Results: [], TotalResults: 0 }
const terms = q.split(/[\s+]+/).filter(Boolean)
const { results } = await db.prepare('SELECT data FROM rooms').all<RoomRow>()
const { results } = await db.prepare('SELECT data FROM room').all<RoomRow>()
let rooms = parseAll(results).filter((r) => r.IsDorm !== true && r.Accessibility === 1)
for (const term of terms) {
@@ -496,7 +517,7 @@ export async function getHotRooms(
skip: number,
take: number
): Promise<{ Results: Room[]; TotalResults: number }> {
const { results } = await db.prepare('SELECT data FROM rooms').all<RoomRow>()
const { results } = await db.prepare('SELECT data FROM room').all<RoomRow>()
let rooms = parseAll(results).filter(
(r) => r.IsDorm !== true && r.Accessibility === 1 && r.ExcludeFromLists !== true
)
@@ -525,7 +546,7 @@ export async function getRecommendedRooms(
skip: number,
take: number
): Promise<Room[]> {
const { results } = await db.prepare('SELECT data FROM rooms').all<RoomRow>()
const { results } = await db.prepare('SELECT data FROM room').all<RoomRow>()
const roomId = (r: Room): number => (typeof r.RoomId === 'number' ? r.RoomId : 0)
return parseAll(results)
.filter((r) => r.IsDorm !== true && r.Accessibility === 1 && r.ExcludeFromLists !== true)
@@ -559,7 +580,7 @@ export interface FeaturedRoomGroup {
* Small dataset, so done in memory.
*/
export async function getFeaturedRooms(db: D1Database): Promise<FeaturedRoomGroup> {
const { results } = await db.prepare('SELECT data FROM rooms').all<RoomRow>()
const { results } = await db.prepare('SELECT data FROM room').all<RoomRow>()
const rooms = parseAll(results).filter(
(r) => r.IsDorm !== true && r.Accessibility === 1 && r.ExcludeFromLists !== true
)
@@ -606,7 +627,7 @@ export async function getSimilarRooms(
const targetTags = new Set(roomTags(target))
if (targetTags.size === 0) return empty
const { results } = await db.prepare('SELECT data FROM rooms').all<RoomRow>()
const { results } = await db.prepare('SELECT data FROM room').all<RoomRow>()
const sharedCount = (r: Room): number => roomTags(r).filter((t) => targetTags.has(t)).length
const roomIdOf = (r: Room): number => (typeof r.RoomId === 'number' ? r.RoomId : 0)
@@ -639,7 +660,7 @@ export async function getSimilarRooms(
* array. Small dataset, so done in memory.
*/
export async function getBaseRooms(db: D1Database, skip: number, take: number): Promise<Room[]> {
const { results } = await db.prepare('SELECT data FROM rooms').all<RoomRow>()
const { results } = await db.prepare('SELECT data FROM room').all<RoomRow>()
const base = new Set(['base'])
const roomIdOf = (r: Room): number => (typeof r.RoomId === 'number' ? r.RoomId : 0)
return parseAll(results)
+35 -35
View File
@@ -5,7 +5,6 @@ import { logger, withNotFound, withOnError } from '@repo/hono-helpers'
import { validateAndGetAccountId } from './jwt'
import {
addRoomTag,
cloneRoom,
findSubRoom,
getBaseRooms,
@@ -30,6 +29,7 @@ import {
setRoomName,
toggleCheer,
toggleFavorite,
toggleRoomTag,
} from './rooms-db'
import type { Context } from 'hono'
@@ -209,18 +209,29 @@ function roomResult(
})
}
/** Client envelope for room clone results: `{ success, error, value }`. */
function cloneResult(c: Context<App>, value: unknown, error = '') {
/** Client envelope for room mutations: `{ success, error, value }` (lowercase). */
function roomEnvelope(c: Context<App>, value: unknown, error = '') {
return c.json({ success: error === '', error, value })
}
/** Rooms created/owned by the authed caller (shared by the createdby/ownedby routes). */
/** Rooms created/owned by the authed caller (shared by the createdby routes). */
async function ownedRooms(c: Context<App>) {
const accountId = await authedAccountId(c)
if (accountId === null) return unauthorized(c)
return c.json(await getRoomsByCreator(c.env.DB, accountId))
}
/**
* The caller's owned rooms, excluding their dorm. The dorm is auto-provisioned,
* not a room the player made, so it doesn't belong in the "rooms you own" list.
*/
async function ownedRoomsExcludingDorm(c: Context<App>) {
const accountId = await authedAccountId(c)
if (accountId === null) return unauthorized(c)
const rooms = await getRoomsByCreator(c.env.DB, accountId)
return c.json(rooms.filter((r) => r.IsDorm !== true))
}
const app = new Hono<App>()
.use(
'*',
@@ -316,10 +327,11 @@ const app = new Hono<App>()
return c.json(room ? [room] : [])
})
// Rooms created/owned by the caller (their dorm). The client calls all three.
// Auth-gated — no token is a 401, never account 1.
// Rooms created/owned by the caller. Auth-gated — no token is a 401, never
// account 1. `ownedby/me` drops the dorm (it's not a room the player made);
// the `createdby` variants return everything the account created.
.get('/roomserver/rooms/createdby/me', ownedRooms)
.get('/rooms/ownedby/me', ownedRooms)
.get('/rooms/ownedby/me', ownedRoomsExcludingDorm)
.get('/rooms/createdby/me', ownedRooms)
// Public: the rooms a given account owns that are publicly viewable. No auth —
@@ -423,9 +435,9 @@ const app = new Hono<App>()
const raw = body.name ?? c.req.query('name') ?? ''
const name = typeof raw === 'string' ? raw.trim() : ''
if (name === '') return cloneResult(c, null, 'You must enter a name for your room.')
if (name === '') return roomEnvelope(c, null, 'You must enter a name for your room.')
if (await getRoomByName(c.env.DB, name)) {
return cloneResult(c, null, 'A room with that name already exists!')
return roomEnvelope(c, null, 'A room with that name already exists!')
}
const room = await cloneRoom(
c.env.DB,
@@ -433,8 +445,8 @@ const app = new Hono<App>()
name,
accountId
)
if (!room) return cloneResult(c, null, "You can't clone this room!")
return cloneResult(c, room)
if (!room) return roomEnvelope(c, null, "You can't clone this room!")
return roomEnvelope(c, room)
})
// Update a room's description. Auth-gated (401) and owner-only. Business results
@@ -515,41 +527,29 @@ const app = new Hono<App>()
return roomResult(c, { Success: true })
})
// Add a tag to a room. Auth-gated (401) and owner-only. Body is the `tag` form
// field; the tag is added as a user tag (Type 0), deduped case-insensitively.
// Business results use the `{ Success, Value, ErrorId, Error }` envelope at 200.
// Toggle a tag on a room. Auth-gated (401) and owner-only. Body is the `tag`
// form field. There's no delete/patch endpoint, so this call toggles: it adds
// the tag (Type 0) if absent and removes it if present. The "main" tags
// (#pvp/#quest/#game/#hangout/#art) are radio buttons — setting one clears the
// others. Returns the `{ success, error, value }` envelope with the updated
// room as `value`; business failures are 200 with success:false.
.put('/rooms/:roomId{[0-9]+}/tags', async (c) => {
const accountId = await authedAccountId(c)
if (accountId === null) return unauthorized(c)
const roomId = Number.parseInt(c.req.param('roomId'), 10)
const room = await getRoomById(c.env.DB, roomId)
if (!room) {
return roomResult(c, {
Success: false,
ErrorId: 'Rooms.DoesntExist',
Error: 'This room does not exist!',
})
}
if (!room) return roomEnvelope(c, null, 'This room does not exist!')
if (room.CreatorAccountId !== accountId) {
return roomResult(c, {
Success: false,
ErrorId: 'Rooms.NotOwner',
Error: 'You are not the owner of this room!',
})
return roomEnvelope(c, null, 'You are not the owner of this room!')
}
const body = (await c.req.parseBody().catch(() => ({}))) as Record<string, unknown>
const tag = typeof body.tag === 'string' ? body.tag.trim() : ''
if (tag === '') {
return roomResult(c, {
Success: false,
ErrorId: 'Rooms.InvalidTag',
Error: 'You must provide a tag!',
})
}
await addRoomTag(c.env.DB, roomId, room, tag)
return roomResult(c, { Success: true })
if (tag === '') return roomEnvelope(c, null, 'You must provide a tag!')
const updated = await toggleRoomTag(c.env.DB, roomId, room, tag)
return roomEnvelope(c, updated)
})
// Set a room's image. Auth-gated (401) and owner-only. Body is the `imageName`
+47 -31
View File
@@ -49,7 +49,7 @@ beforeAll(async () => {
await adminSecretsStore(env.JWT_SECRET).create('test-signing-key')
for (const stmt of SCHEMA_DDL) await env.DB.prepare(stmt).run()
for (const stmt of ROOM_INSTANCE_SCHEMA_DDL) await env.DB.prepare(stmt).run()
const insert = env.DB.prepare('INSERT OR IGNORE INTO rooms (data) VALUES (?1)')
const insert = env.DB.prepare('INSERT OR IGNORE INTO room (data) VALUES (?1)')
await env.DB.batch(importRooms.map((r) => insert.bind(JSON.stringify(r))))
})
@@ -111,11 +111,13 @@ describe('rooms endpoints', () => {
// No token → 401, no stub-account fallback (would otherwise leak account 1).
const noAuth = await SELF.fetch(`${ORIGIN}/rooms/ownedby/me`)
expect(noAuth.status).toBe(401)
// Account 1 owns all the seeded rooms.
// Account 1 owns all the seeded rooms, but the dorm is excluded here.
const mine = (await (
await SELF.fetch(`${ORIGIN}/rooms/ownedby/me`, { headers: await bearer('1') })
).json()) as unknown[]
expect(mine.length).toBe(importRooms.length)
).json()) as Array<{ RoomId: number; IsDorm?: boolean }>
expect(mine.length).toBe(importRooms.filter((r) => r.IsDorm !== true).length)
// The dorm (RoomId 1) is auto-provisioned, so it never appears.
expect(mine.some((r) => r.RoomId === 1 || r.IsDorm === true)).toBe(false)
// A different account owns none of them.
const other = (await (
await SELF.fetch(`${ORIGIN}/rooms/ownedby/me`, { headers: await bearer('999') })
@@ -659,40 +661,54 @@ describe('rooms endpoints', () => {
expect(await bodyOf(coOwner)).toMatchObject({ SubRoomId: 2, CreatorAccountId: 1 })
})
it('PUT /rooms/:id/tags is auth-gated, owner-only, dedupes, and persists', async () => {
it('PUT /rooms/:id/tags is auth-gated, owner-only, and toggles (add/remove)', async () => {
// The lowercase `{ success, error, value }` envelope this endpoint returns.
type TagResult = { success: boolean; error: string; value: { Tags?: Array<{ Tag: string }> } | null }
const envOf = async (res: Response) => (await res.json()) as TagResult
const tagsIn = (r: TagResult) => (r.value?.Tags ?? []).map((t) => t.Tag)
// No token → 401.
expect((await putForm('/rooms/2/tags', { tag: 'quest' })).status).toBe(401)
// Not the owner → NotOwner envelope.
expect(await bodyOf(await putForm('/rooms/2/tags', { tag: 'quest' }, '999'))).toMatchObject({
Success: false,
ErrorId: 'Rooms.NotOwner',
// Not the owner → failure envelope.
expect(await envOf(await putForm('/rooms/2/tags', { tag: 'quest' }, '999'))).toMatchObject({
success: false,
error: 'You are not the owner of this room!',
})
// Unknown room → DoesntExist.
expect(await bodyOf(await putForm('/rooms/99999/tags', { tag: 'quest' }, '1'))).toMatchObject({
Success: false,
ErrorId: 'Rooms.DoesntExist',
// Unknown room → failure envelope.
expect(await envOf(await putForm('/rooms/99999/tags', { tag: 'quest' }, '1'))).toMatchObject({
success: false,
error: 'This room does not exist!',
})
// Empty tag → InvalidTag.
expect(await bodyOf(await putForm('/rooms/2/tags', { tag: ' ' }, '1'))).toMatchObject({
Success: false,
ErrorId: 'Rooms.InvalidTag',
// Empty tag → failure envelope.
expect(await envOf(await putForm('/rooms/2/tags', { tag: ' ' }, '1'))).toMatchObject({
success: false,
error: 'You must provide a tag!',
})
// Owner adds a tag → it persists as a Type-0 user tag.
expect(await bodyOf(await putForm('/rooms/2/tags', { tag: 'quest' }, '1'))).toMatchObject({
Success: true,
})
const tagsOf = async () =>
(
(await (await SELF.fetch(`${ORIGIN}/rooms/2`)).json()) as {
Tags: Array<{ Tag: string; Type: number }>
}
).Tags
expect(await tagsOf()).toContainEqual({ Tag: 'quest', Type: 0 })
// Owner adds a non-main tag → success envelope carries the updated room.
const added = await envOf(await putForm('/rooms/2/tags', { tag: 'spooky' }, '1'))
expect(added).toMatchObject({ success: true, error: '' })
expect(tagsIn(added)).toContain('spooky')
// Adding the same tag again (different case) is a no-op — no duplicate.
await putForm('/rooms/2/tags', { tag: 'QUEST' }, '1')
expect((await tagsOf()).filter((t) => t.Tag.toLowerCase() === 'quest')).toHaveLength(1)
// The same call again toggles it back off (no delete endpoint).
const removed = await envOf(await putForm('/rooms/2/tags', { tag: 'SPOOKY' }, '1'))
expect(tagsIn(removed)).not.toContain('spooky')
// Main tags are radio buttons: setting one clears any other main tag, but
// leaves non-main tags alone.
await putForm('/rooms/2/tags', { tag: 'campfire' }, '1') // non-main, stays put
const pvp = await envOf(await putForm('/rooms/2/tags', { tag: 'pvp' }, '1'))
expect(tagsIn(pvp)).toEqual(expect.arrayContaining(['pvp', 'campfire']))
const quest = await envOf(await putForm('/rooms/2/tags', { tag: 'quest' }, '1'))
expect(tagsIn(quest)).toContain('quest')
expect(tagsIn(quest)).not.toContain('pvp') // the previous main tag was cleared
expect(tagsIn(quest)).toContain('campfire') // non-main tag untouched
// Toggling the current main tag off just removes it (no other change).
const off = await envOf(await putForm('/rooms/2/tags', { tag: 'quest' }, '1'))
expect(tagsIn(off)).not.toContain('quest')
expect(tagsIn(off)).toContain('campfire')
})
it('PUT /rooms/:id/name is auth-gated, owner-only, unique, and persists', async () => {