Skip to content
File

Blob: src/worker/api/private/shared.ts

typescript42 lines
1import { ProjectId } from "@/contracts";
2import { toCodecIssueDetails } from "@/lib/codec-errors";
3import { findOwnedProjectById, type ProjectRow } from "@/worker/db/d1/repositories";
4import type { AppContext } from "@/worker/hono";
5import { HttpError } from "@/worker/http";
6 
7export interface OwnedProjectResolution {
8 projectId: ProjectId;
9 project: ProjectRow;
10}
11 
12export 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 
20export 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 
28export 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};