-
-
Save kaldaf/21701315b828cdf1f05bd38d8d46362b to your computer and use it in GitHub Desktop.
Deno KV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; | |
| const db = await Deno.openKv(); | |
| interface RouteHandler { | |
| [key: string]: (url: URL) => Promise<{ body: string; status?: number }>; | |
| } | |
| const template = `\n\rtry /reset or /set?value=[your value]` | |
| const routes: RouteHandler = { | |
| "/": async () => { | |
| const pageViews = await db.get(["pageViews"]); | |
| await db.atomic().mutate({type: "sum", ["pageViews"], value: new Deno.KvU64(1n)}).commit(); | |
| return { body: `Total views: ${pageViews.value + 1}` + template }; | |
| }, | |
| "/set": async (url: URL) => { | |
| const value = url.searchParams.get("value"); | |
| if (value === null || /^\d+$/.test(value)) { | |
| await db.set(["pageViews"], value ? parseInt(value) : 0); | |
| return { body: `${value}` }; | |
| } | |
| return { body: "NOT OK", status: 400 }; | |
| }, | |
| "/reset": async () => { | |
| await db.set(["pageViews"], 0); | |
| return { body: "OK" }; | |
| }, | |
| "*": async () => { | |
| return { body: "I'm a teapot", status: 418 }; | |
| }, | |
| }; | |
| serve(async (req: Request) => { | |
| const url = new URL(req.url); | |
| const handler = routes[url.pathname] ?? routes["*"]; | |
| const res = await handler(url); | |
| return new Response(res.body, { status: res.status ?? 200 }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment