|
| 1 | +import uuid |
| 2 | + |
| 3 | +from fastapi import FastAPI, Request |
| 4 | +from fastapi.middleware.cors import CORSMiddleware |
| 5 | +from workers import WorkerEntrypoint |
| 6 | + |
| 7 | +app = FastAPI() |
| 8 | + |
| 9 | +app.add_middleware( |
| 10 | + CORSMiddleware, |
| 11 | + allow_origins=["*"], |
| 12 | + allow_methods=["*"], |
| 13 | + allow_headers=["*"], |
| 14 | + expose_headers=["*"], |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +def _base_url(request: Request) -> str: |
| 19 | + """Return the root URL for the todos collection.""" |
| 20 | + return str(request.base_url).rstrip("/") + "/todos" |
| 21 | + |
| 22 | + |
| 23 | +def _row_to_todo(row, request: Request) -> dict: |
| 24 | + """Convert a D1 row into a todo dict with the absolute ``url`` field.""" |
| 25 | + return { |
| 26 | + "id": row.id, |
| 27 | + "title": row.title, |
| 28 | + "completed": bool(row.completed), |
| 29 | + "order": row.order, |
| 30 | + "url": f"{_base_url(request)}/{row.id}", |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | +def _db(request: Request): |
| 35 | + """Get the D1 database binding from the ASGI scope.""" |
| 36 | + return request.scope["env"].DB |
| 37 | + |
| 38 | + |
| 39 | +@app.get("/todos") |
| 40 | +async def list_todos(request: Request): |
| 41 | + results = await _db(request).prepare("SELECT * FROM todos").all() |
| 42 | + return [_row_to_todo(r, request) for r in results.results] |
| 43 | + |
| 44 | + |
| 45 | +@app.post("/todos") |
| 46 | +async def create_todo(request: Request): |
| 47 | + body = await request.json() |
| 48 | + todo_id = str(uuid.uuid4()) |
| 49 | + title = body.get("title", "") |
| 50 | + completed = 1 if body.get("completed", False) else 0 |
| 51 | + order = body.get("order") |
| 52 | + |
| 53 | + await ( |
| 54 | + _db(request) |
| 55 | + .prepare( |
| 56 | + 'INSERT INTO todos (id, title, completed, "order") VALUES (?, ?, ?, ?)' |
| 57 | + ) |
| 58 | + .bind(todo_id, title, completed, order) |
| 59 | + .run() |
| 60 | + ) |
| 61 | + |
| 62 | + row = ( |
| 63 | + await _db(request) |
| 64 | + .prepare("SELECT * FROM todos WHERE id = ?") |
| 65 | + .bind(todo_id) |
| 66 | + .first() |
| 67 | + ) |
| 68 | + |
| 69 | + return _row_to_todo(row, request) |
| 70 | + |
| 71 | + |
| 72 | +@app.delete("/todos") |
| 73 | +async def delete_all_todos(request: Request): |
| 74 | + await _db(request).prepare("DELETE FROM todos").run() |
| 75 | + return [] |
| 76 | + |
| 77 | + |
| 78 | +@app.get("/todos/{todo_id}") |
| 79 | +async def get_todo(todo_id: str, request: Request): |
| 80 | + row = ( |
| 81 | + await _db(request) |
| 82 | + .prepare("SELECT * FROM todos WHERE id = ?") |
| 83 | + .bind(todo_id) |
| 84 | + .first() |
| 85 | + ) |
| 86 | + if row is None: |
| 87 | + return {"error": "not found"} |
| 88 | + return _row_to_todo(row, request) |
| 89 | + |
| 90 | + |
| 91 | +@app.patch("/todos/{todo_id}") |
| 92 | +async def update_todo(todo_id: str, request: Request): |
| 93 | + body = await request.json() |
| 94 | + sets = [] |
| 95 | + values = [] |
| 96 | + if "title" in body: |
| 97 | + sets.append("title = ?") |
| 98 | + values.append(body["title"]) |
| 99 | + if "completed" in body: |
| 100 | + sets.append("completed = ?") |
| 101 | + values.append(1 if body["completed"] else 0) |
| 102 | + if "order" in body: |
| 103 | + sets.append('"order" = ?') |
| 104 | + values.append(body["order"]) |
| 105 | + |
| 106 | + if sets: |
| 107 | + values.append(todo_id) |
| 108 | + await ( |
| 109 | + _db(request) |
| 110 | + .prepare(f"UPDATE todos SET {', '.join(sets)} WHERE id = ?") |
| 111 | + .bind(*values) |
| 112 | + .run() |
| 113 | + ) |
| 114 | + |
| 115 | + row = ( |
| 116 | + await _db(request) |
| 117 | + .prepare("SELECT * FROM todos WHERE id = ?") |
| 118 | + .bind(todo_id) |
| 119 | + .first() |
| 120 | + ) |
| 121 | + if row is None: |
| 122 | + return {"error": "not found"} |
| 123 | + return _row_to_todo(row, request) |
| 124 | + |
| 125 | + |
| 126 | +@app.delete("/todos/{todo_id}") |
| 127 | +async def delete_todo(todo_id: str, request: Request): |
| 128 | + await _db(request).prepare("DELETE FROM todos WHERE id = ?").bind(todo_id).run() |
| 129 | + return [] |
| 130 | + |
| 131 | +import asgi |
| 132 | +Default = asgi.entrypoint(app) |
0 commit comments