Open History to see the last commit
1import { eq } from "drizzle-orm";
2import z from "zod";
3import { db } from "@/db";
4import { todoItemsTable } from "@/db/schema";
5import { todoItemUpdateData } from "./api.todo-items";
6import { type APIRouteHandler, json } from "./helpers";
7
8const todoItemBatchUpdateData = z.array(todoItemUpdateData);
9
10export default {
11 PATCH: async ({ request }) => {
12 // Update multiple todo items at once
13
14 let updatedData: z.infer<typeof todoItemUpdateData>[];
15
16 // biome-ignore lint/suspicious/noExplicitAny: it can be any here
17 let bodyObj: any;
18
19 try {
20 bodyObj = await request.json();
21 } catch (e) {
22 console.error("Error parsing JSON body:", e);
23 return new Response(`Invalid JSON body`, { status: 400 });
24 }
25
26 try {
27 updatedData = todoItemBatchUpdateData.parse(bodyObj);
28 } catch (e) {
29 console.error("Validation error:", e);
30 if (e instanceof z.ZodError) {
31 return new Response(`Invalid request data: ${z.prettifyError(e)}`, {
32 status: 400,
33 });
34 }
35 console.error("Bad format", e);
36 return new Response(`Validation error`, { status: 400 });
37 }
38
39 await db.transaction(async (tx) => {
40 for (const todoItemData of updatedData) {
41 await tx
42 .update(todoItemsTable)
43 .set(todoItemData)
44 .where(eq(todoItemsTable.id, todoItemData.id));
45 }
46 });
47
48 return json({ updated: "ok" });
49 },
50} satisfies APIRouteHandler;