85 lines
2.4 KiB
TypeScript
85 lines
2.4 KiB
TypeScript
import { Hono } from "hono"
|
|
import { castVoteSchema } from "./schema"
|
|
import {
|
|
castVote,
|
|
deleteMockLegislation,
|
|
getLegislation,
|
|
getLegislationResults,
|
|
getLegislationText,
|
|
getUpcomingLegislation,
|
|
getUserVote,
|
|
seedMockLegislation,
|
|
} from "./service"
|
|
|
|
export const legislationRouter = new Hono()
|
|
|
|
// static routes FIRST — before /:id param routes
|
|
legislationRouter.post("/seed-mock", async (c) => {
|
|
const ids = await seedMockLegislation()
|
|
return c.json({ ok: true, count: ids.length, ids }, 201)
|
|
})
|
|
|
|
legislationRouter.delete("/seed-mock", async (c) => {
|
|
const count = await deleteMockLegislation()
|
|
return c.json({ ok: true, deleted: count })
|
|
})
|
|
|
|
legislationRouter.get("/upcoming", async (c) => {
|
|
const items = await getUpcomingLegislation()
|
|
return c.json(items)
|
|
})
|
|
|
|
legislationRouter.get("/:id", async (c) => {
|
|
const id = Number(c.req.param("id"))
|
|
if (Number.isNaN(id)) return c.json({ error: "invalid id" }, 400)
|
|
|
|
const legislation = await getLegislation(id)
|
|
if (!legislation) return c.json({ error: "not found" }, 404)
|
|
|
|
return c.json(legislation)
|
|
})
|
|
|
|
legislationRouter.get("/:id/text", async (c) => {
|
|
const id = Number(c.req.param("id"))
|
|
if (Number.isNaN(id)) return c.json({ error: "invalid id" }, 400)
|
|
|
|
const text = await getLegislationText(id)
|
|
if (text === null) return c.json({ error: "not found" }, 404)
|
|
|
|
return c.json({ text })
|
|
})
|
|
|
|
legislationRouter.post("/:id/vote", async (c) => {
|
|
const id = Number(c.req.param("id"))
|
|
if (Number.isNaN(id)) return c.json({ error: "invalid id" }, 400)
|
|
|
|
const body = await c.req.json()
|
|
const parsed = castVoteSchema.safeParse(body)
|
|
if (!parsed.success) return c.json({ error: parsed.error.flatten() }, 400)
|
|
|
|
await castVote(id, parsed.data)
|
|
return c.json({ ok: true }, 201)
|
|
})
|
|
|
|
legislationRouter.get("/:id/results/:deviceId", async (c) => {
|
|
const id = Number(c.req.param("id"))
|
|
const deviceId = c.req.param("deviceId")
|
|
if (Number.isNaN(id)) return c.json({ error: "invalid id" }, 400)
|
|
|
|
const results = await getLegislationResults(id, deviceId)
|
|
if (!results) return c.json({ error: "no results yet" }, 404)
|
|
|
|
return c.json(results)
|
|
})
|
|
|
|
legislationRouter.get("/:id/vote/:deviceId", async (c) => {
|
|
const id = Number(c.req.param("id"))
|
|
const deviceId = c.req.param("deviceId")
|
|
if (Number.isNaN(id)) return c.json({ error: "invalid id" }, 400)
|
|
|
|
const vote = await getUserVote(id, deviceId)
|
|
if (!vote) return c.json({ error: "no vote found" }, 404)
|
|
|
|
return c.json(vote)
|
|
})
|