Spaces:
Runtime error
Runtime error
| import { Router } from "express"; | |
| import { db, tasksTable } from "@workspace/db"; | |
| import { eq, and } from "drizzle-orm"; | |
| import { | |
| CreateTaskBody, | |
| UpdateTaskBody, | |
| ListTasksQueryParams, | |
| UpdateTaskParams, | |
| DeleteTaskParams, | |
| } from "@workspace/api-zod"; | |
| const router = Router(); | |
| router.get("/tasks", async (req, res) => { | |
| const query = ListTasksQueryParams.safeParse(req.query); | |
| if (!query.success) { | |
| res.status(400).json({ error: query.error.message }); | |
| return; | |
| } | |
| let { projectId, done } = query.data; | |
| if (req.query.done === "false") { | |
| done = false; | |
| } else if (req.query.done === "true") { | |
| done = true; | |
| } | |
| const conditions = [eq(tasksTable.userId, req.user!.id)]; | |
| if (projectId !== undefined) conditions.push(eq(tasksTable.projectId, projectId)); | |
| if (done !== undefined) conditions.push(eq(tasksTable.done, done)); | |
| const tasks = await db | |
| .select() | |
| .from(tasksTable) | |
| .where(conditions.length > 0 ? and(...conditions) : undefined) | |
| .orderBy(tasksTable.createdAt); | |
| res.json(tasks); | |
| }); | |
| router.post("/tasks", async (req, res) => { | |
| const body = CreateTaskBody.safeParse(req.body); | |
| if (!body.success) { | |
| res.status(400).json({ error: body.error.message }); | |
| return; | |
| } | |
| const [task] = await db.insert(tasksTable).values({ ...body.data, userId: req.user!.id }).returning(); | |
| res.status(201).json(task); | |
| }); | |
| router.patch("/tasks/:id", async (req, res) => { | |
| const params = UpdateTaskParams.safeParse({ id: Number(req.params.id) }); | |
| if (!params.success) { | |
| res.status(400).json({ error: params.error.message }); | |
| return; | |
| } | |
| const body = UpdateTaskBody.safeParse(req.body); | |
| if (!body.success) { | |
| res.status(400).json({ error: body.error.message }); | |
| return; | |
| } | |
| const updateData = { ...body.data }; | |
| const [task] = await db | |
| .update(tasksTable) | |
| .set(updateData) | |
| .where(and(eq(tasksTable.id, params.data.id), eq(tasksTable.userId, req.user!.id))) | |
| .returning(); | |
| if (!task) { | |
| res.status(404).json({ error: "Task not found" }); | |
| return; | |
| } | |
| res.json(task); | |
| }); | |
| router.delete("/tasks/:id", async (req, res) => { | |
| const params = DeleteTaskParams.safeParse({ id: Number(req.params.id) }); | |
| if (!params.success) { | |
| res.status(400).json({ error: params.error.message }); | |
| return; | |
| } | |
| await db.delete(tasksTable).where(and(eq(tasksTable.id, params.data.id), eq(tasksTable.userId, req.user!.id))); | |
| res.status(204).send(); | |
| }); | |
| export default router; | |