Something went wrong. Try again.
spool is a community-first, lightweight discussion forum, issue tracker, and announcement hub for your project.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312import { and, asc, count, desc, eq } from "drizzle-orm";import { Hono } from "hono";import { nextIssueNumber, slugify } from "../db/helpers.js";import { db } from "../db/index.js";import { comments, issues, messages, spools, users } from "../db/schema.js";import { requireAuth, type AuthEnv } from "../auth/session.js";
const router = new Hono<AuthEnv>();
function spoolSelection() { return { id: spools.id, slug: spools.slug, name: spools.name, description: spools.description, repoUrl: spools.repoUrl, ownerId: spools.ownerId, threadsLocked: spools.threadsLocked, owner: users.username, createdAt: spools.createdAt, };}
async function spoolBySlug(slug: string) { const [spool] = await db .select(spoolSelection()) .from(spools) .innerJoin(users, eq(spools.ownerId, users.id)) .where(eq(spools.slug, slug)); return spool;}
// Whether `userId` may start a new thread in this spool: always true when// unlocked or when they're the owner; otherwise only "contributors" — anyone// who has already posted a thread message, opened an issue, or commented on// one here before (no separate membership table yet).async function canStartThread( spool: { id: number; ownerId: number; threadsLocked: boolean }, userId: number | null) { if (!userId) return false; if (!spool.threadsLocked || userId === spool.ownerId) return true;
const [priorMessage] = await db .select({ id: messages.id }) .from(messages) .where(and(eq(messages.spoolId, spool.id), eq(messages.authorId, userId))); if (priorMessage) return true;
const [priorIssue] = await db .select({ id: issues.id }) .from(issues) .where(and(eq(issues.spoolId, spool.id), eq(issues.authorId, userId))); if (priorIssue) return true;
const [priorComment] = await db .select({ id: comments.id }) .from(comments) .innerJoin(issues, eq(comments.issueId, issues.id)) .where(and(eq(issues.spoolId, spool.id), eq(comments.authorId, userId))); return !!priorComment;}
// GET /api/spoolsrouter.get("/", async (c) => { const rows = await db .select(spoolSelection()) .from(spools) .innerJoin(users, eq(spools.ownerId, users.id)) .orderBy(desc(spools.createdAt));
const issueCounts = await db .select({ spoolId: issues.spoolId, status: issues.status, n: count() }) .from(issues) .groupBy(issues.spoolId, issues.status);
const result = rows.map((s) => { const counts = issueCounts.filter((ic) => ic.spoolId === s.id); const open = counts .filter((ic) => ic.status === "open" || ic.status === "in_progress") .reduce((sum, ic) => sum + ic.n, 0); const total = counts.reduce((sum, ic) => sum + ic.n, 0); return { ...s, openIssues: open, totalIssues: total }; });
return c.json(result);});
// POST /api/spools — create a spool (auth required); creator becomes ownerrouter.post("/", requireAuth, async (c) => { const data = await c.req.json<{ name?: string; description?: string; repoUrl?: string }>(); const name = data.name?.trim(); if (!name) return c.json({ error: "Name is required" }, 400);
const slug = slugify(name); if (!slug) return c.json({ error: "Name must contain letters or numbers" }, 400);
const existing = await db.select({ id: spools.id }).from(spools).where(eq(spools.slug, slug)); if (existing.length > 0) return c.json({ error: `A spool named "${slug}" already exists` }, 409);
const [spool] = await db .insert(spools) .values({ slug, name, description: data.description?.trim() || null, repoUrl: data.repoUrl?.trim() || null, ownerId: c.get("user")!.id, }) .returning();
return c.json(spool, 201);});
// GET /api/spools/:slug — one spool's metadata (used by the spool layout)router.get("/:slug", async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404); const userId = c.get("user")?.id ?? null; return c.json({ ...spool, canStartThread: await canStartThread(spool, userId) });});
// PATCH /api/spools/:slug — update settings (owner only)router.patch("/:slug", requireAuth, async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404); if (spool.ownerId !== c.get("user")!.id) { return c.json({ error: "Only the spool owner can change its settings" }, 403); }
const data = await c.req.json<{ description?: string | null; repoUrl?: string | null; threadsLocked?: boolean; }>();
await db .update(spools) .set({ ...(data.description !== undefined && { description: data.description?.trim() || null }), ...(data.repoUrl !== undefined && { repoUrl: data.repoUrl?.trim() || null }), ...(data.threadsLocked !== undefined && { threadsLocked: data.threadsLocked }), }) .where(eq(spools.id, spool.id));
return c.json(await spoolBySlug(spool.slug));});
// GET /api/spools/:slug/threads — this spool's thread messages, oldest firstrouter.get("/:slug/threads", async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404);
const rows = await db .select({ id: messages.id, parentId: messages.parentId, body: messages.body, author: users.username, authorAvatar: users.avatarUrl, cutIssueNumber: issues.number, createdAt: messages.createdAt, }) .from(messages) .innerJoin(users, eq(messages.authorId, users.id)) .leftJoin(issues, eq(issues.sourceMessageId, messages.id)) .where(eq(messages.spoolId, spool.id)) .orderBy(asc(messages.createdAt));
return c.json(rows);});
// POST /api/spools/:slug/threads — start a thread, or reply to one (auth required)router.post("/:slug/threads", requireAuth, async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404);
const data = await c.req.json<{ body?: string; parentId?: number }>(); const text = data.body?.trim(); if (!text) return c.json({ error: "Message body is required" }, 400);
const authorId = c.get("user")!.id;
// Locking only restricts starting new threads — replies stay open to everyone. if (data.parentId == null && !(await canStartThread(spool, authorId))) { return c.json({ error: "This spool only accepts new threads from contributors" }, 403); }
let parentId: number | null = null; if (data.parentId != null) { const [parent] = await db .select({ id: messages.id, parentId: messages.parentId, spoolId: messages.spoolId }) .from(messages) .where(eq(messages.id, data.parentId)); if (!parent || parent.spoolId !== spool.id) { return c.json({ error: "Message not found" }, 404); } // Replying to a reply attaches to the root — threads stay one level deep. parentId = parent.parentId ?? parent.id; }
const [message] = await db .insert(messages) .values({ spoolId: spool.id, authorId: c.get("user")!.id, body: text, parentId }) .returning();
return c.json(message, 201);});
// GET /api/spools/:slug/issues — this spool's issue listrouter.get("/:slug/issues", async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404);
const rows = await db .select({ id: issues.id, number: issues.number, title: issues.title, status: issues.status, author: users.username, commentCount: count(comments.id), createdAt: issues.createdAt, }) .from(issues) .innerJoin(users, eq(issues.authorId, users.id)) .leftJoin(comments, eq(comments.issueId, issues.id)) .where(eq(issues.spoolId, spool.id)) .groupBy(issues.id) .orderBy(desc(issues.number));
return c.json(rows);});
// GET /api/spools/:slug/issues/:number — issue detail + comments.// Addressed by per-spool number (what URLs show); the response carries the// global `id` the client needs for mutations (status, title, comments).router.get("/:slug/issues/:number", async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404);
const number = Number(c.req.param("number")); const [issue] = await db .select({ id: issues.id, number: issues.number, title: issues.title, body: issues.body, status: issues.status, author: users.username, authorAvatar: users.avatarUrl, sourceMessageId: issues.sourceMessageId, createdAt: issues.createdAt, }) .from(issues) .innerJoin(users, eq(issues.authorId, users.id)) .where(and(eq(issues.spoolId, spool.id), eq(issues.number, number)));
if (!issue) return c.json({ error: "Issue not found" }, 404);
// If this issue was cut from a thread, credit the original poster. let source: { messageId: number; author: string } | null = null; if (issue.sourceMessageId != null) { const [msg] = await db .select({ author: users.username }) .from(messages) .innerJoin(users, eq(messages.authorId, users.id)) .where(eq(messages.id, issue.sourceMessageId)); if (msg) source = { messageId: issue.sourceMessageId, author: msg.author }; }
const commentRows = await db .select({ id: comments.id, body: comments.body, author: users.username, authorAvatar: users.avatarUrl, createdAt: comments.createdAt, }) .from(comments) .innerJoin(users, eq(comments.authorId, users.id)) .where(eq(comments.issueId, issue.id)) .orderBy(asc(comments.createdAt));
return c.json({ ...issue, source, comments: commentRows });});
// POST /api/spools/:slug/issues — open an issue (auth required)router.post("/:slug/issues", requireAuth, async (c) => { const spool = await spoolBySlug(c.req.param("slug")); if (!spool) return c.json({ error: "Spool not found" }, 404);
const data = await c.req.json<{ title?: string; body?: string }>(); const title = data.title?.trim(); if (!title) return c.json({ error: "Title is required" }, 400);
const [issue] = await db .insert(issues) .values({ spoolId: spool.id, number: await nextIssueNumber(spool.id), authorId: c.get("user")!.id, title, body: data.body?.trim() ?? "", }) .returning();
return c.json(issue, 201);});
export default router;