| 16 | |
| 17 | // Request handler |
| 18 | async function handler(request: Request): Promise<Response> { |
| 19 | const url = new URL(request.url); |
| 20 | const path = url.pathname; |
| 21 | const method = request.method; |
| 22 | |
| 23 | try { |
| 24 | // GET /tasks - List all tasks |
| 25 | if (method === "GET" && path === "/tasks") { |
| 26 | const tasks = await prisma.task.findMany({ |
| 27 | orderBy: { createdAt: "desc" }, |
| 28 | }); |
| 29 | return json(tasks); |
| 30 | } |
| 31 | |
| 32 | // POST /tasks - Create a new task |
| 33 | if (method === "POST" && path === "/tasks") { |
| 34 | const body = await request.json(); |
| 35 | const task = await prisma.task.create({ |
| 36 | data: { |
| 37 | title: body.title, |
| 38 | description: body.description, |
| 39 | }, |
| 40 | }); |
| 41 | return json(task, 201); |
| 42 | } |
| 43 | |
| 44 | // GET /tasks/:id - Get a specific task |
| 45 | const taskMatch = path.match(/^\/tasks\/(\d+)$/); |
| 46 | if (taskMatch) { |
| 47 | const id = parseInt(taskMatch[1]); |
| 48 | |
| 49 | if (method === "GET") { |
| 50 | const task = await prisma.task.findUnique({ where: { id } }); |
| 51 | if (!task) return json({ error: "Task not found" }, 404); |
| 52 | return json(task); |
| 53 | } |
| 54 | |
| 55 | // PATCH /tasks/:id - Update a task |
| 56 | if (method === "PATCH") { |
| 57 | const body = await request.json(); |
| 58 | const task = await prisma.task.update({ |
| 59 | where: { id }, |
| 60 | data: body, |
| 61 | }); |
| 62 | return json(task); |
| 63 | } |
| 64 | |
| 65 | // DELETE /tasks/:id - Delete a task |
| 66 | if (method === "DELETE") { |
| 67 | await prisma.task.delete({ where: { id } }); |
| 68 | return json({ message: "Task deleted" }); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // GET / - API info |
| 73 | if (method === "GET" && path === "/") { |
| 74 | return json({ |
| 75 | name: "Prisma + Deno Task API", |