Open History to see the last commit
1import { asc, eq } from "drizzle-orm";
2import { z } from "zod";
3import { db } from "@/db";
4import { projectsTable } from "@/db/schema";
5import { projectErrorNames } from "@/utils/errorNames";
6import { type APIRouteHandler, json } from "./helpers";
7
8const projectUpdateData = z.object({
9 id: z.string(),
10 name: z.string().optional(),
11 description: z.string().optional(),
12 itemPositionsInTheProject: z
13 .record(z.string(), z.array(z.string()))
14 .optional(),
15});
16
17export type ProjectUpdateData = z.infer<typeof projectUpdateData>;
18
19const handlers = {
20 GET: async () => {
21 const results = await db
22 .select()
23 .from(projectsTable)
24 .orderBy(asc(projectsTable.createdAt));
25
26 return json(results);
27 },
28 PATCH: async ({ request }) => {
29 let updatedData: z.infer<typeof projectUpdateData>;
30
31 // biome-ignore lint/suspicious/noExplicitAny: it can be any here
32 let bodyObj: any;
33
34 try {
35 bodyObj = await request.json();
36 } catch (e) {
37 console.error("Error parsing JSON body:", e);
38 return new Response(`Invalid JSON body`, { status: 400 });
39 }
40
41 try {
42 updatedData = projectUpdateData.parse(bodyObj);
43 } catch (e) {
44 console.error("Validation error:", e);
45 if (e instanceof z.ZodError) {
46 return new Response(`Invalid request data: ${z.prettifyError(e)}`, {
47 status: 400,
48 });
49 }
50 console.error("Bad format", e);
51 return new Response(`Validation error`, { status: 400 });
52 }
53
54 if (
55 Object.keys(updatedData).length === 1 // there keys other than id
56 ) {
57 return new Response(`No columns to update`, { status: 400 });
58 }
59
60 try {
61 await db
62 .update(projectsTable)
63 .set(updatedData)
64 .where(eq(projectsTable.id, updatedData.id));
65 } catch (error) {
66 if (
67 error instanceof Error &&
68 error.cause instanceof Error &&
69 updatedData.name &&
70 error.cause.message.includes("unique constraint")
71 ) {
72 return new Response(
73 `${projectErrorNames.PROJECT_NAME_EXISTS}: "${updatedData.name}" `,
74 { status: 409 },
75 );
76 }
77
78 console.error("Error updating project:", error);
79 return new Response(
80 `Error updating project: ${error instanceof Error ? error.message : "unkown error"}`,
81 {
82 status: 500,
83 },
84 );
85 }
86
87 return json({
88 updated: "ok",
89 });
90 },
91} satisfies APIRouteHandler;
92
93export default handlers;