File
Blob: src/worker/api/private/shared.ts
| 1 | import { ProjectId } from "@/contracts"; |
| 2 | import { toCodecIssueDetails } from "@/lib/codec-errors"; |
| 3 | import { findOwnedProjectById, type ProjectRow } from "@/worker/db/d1/repositories"; |
| 4 | import type { AppContext } from "@/worker/hono"; |
| 5 | import { HttpError } from "@/worker/http"; |
| 6 | |
| 7 | export interface OwnedProjectResolution { |
| 8 | projectId: ProjectId; |
| 9 | project: ProjectRow; |
| 10 | } |
| 11 | |
| 12 | export const decodeProjectIdParam = (projectId: string): ProjectId => { |
| 13 | try { |
| 14 | return ProjectId.assertDecode(projectId); |
| 15 | } catch (error) { |
| 16 | throw new HttpError(404, "project_not_found", "Project was not found.", toCodecIssueDetails(error)); |
| 17 | } |
| 18 | }; |
| 19 | |
| 20 | export const findOwnedProjectForCurrentUser = async ( |
| 21 | c: AppContext, |
| 22 | projectId: ProjectId, |
| 23 | ): Promise<ProjectRow | undefined> => { |
| 24 | const user = c.get("user"); |
| 25 | return await findOwnedProjectById(c.get("db"), user.id, projectId); |
| 26 | }; |
| 27 | |
| 28 | export const requireOwnedProject = async (c: AppContext): Promise<OwnedProjectResolution> => { |
| 29 | const projectId = c.req.param("projectId"); |
| 30 | if (!projectId) { |
| 31 | throw new HttpError(404, "project_not_found", "Project was not found."); |
| 32 | } |
| 33 | |
| 34 | const decodedProjectId = decodeProjectIdParam(projectId); |
| 35 | const project = await findOwnedProjectForCurrentUser(c, decodedProjectId); |
| 36 | if (!project) { |
| 37 | throw new HttpError(404, "project_not_found", "Project was not found."); |
| 38 | } |
| 39 | |
| 40 | return { projectId: decodedProjectId, project }; |
| 41 | }; |