Created
July 29, 2024 19:05
-
-
Save sbmsr/e83b4436713478830518e25156b8ee0d to your computer and use it in GitHub Desktop.
recurse db server
This file contains 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
const DB: Record<string, string> = {}; | |
Deno.serve({ port: 4000 }, (req: Request) => { | |
const reqUrl = new URL(req.url); | |
switch (reqUrl.pathname) { | |
case "/get": { | |
try { | |
const key = parseGetParams(reqUrl.searchParams); | |
if (Object.keys(DB).includes(key)) return res(200, DB[key]); | |
return res(404, { error: `DB key "${key}" not found in db.` }); | |
} catch (e: unknown) { | |
const error = e instanceof Error ? e.message : "Unknown error"; | |
return res(400, { error }); | |
} | |
} | |
case "/set": { | |
const keys = [...reqUrl.searchParams.keys()]; | |
for (const key of keys) { | |
DB[key] = reqUrl.searchParams.get(key) ?? "null"; | |
} | |
return res(200, { status: "OK" }); | |
} | |
default: | |
return res(200, DB); | |
} | |
}); | |
const parseGetParams = (params: URLSearchParams) => { | |
const validParamKey = "key"; | |
const submittedKeys = new Set([...params.keys()]); | |
if (!submittedKeys.has(validParamKey)) { | |
throw new Error(`Expected param with key of "key", but instead received "${Array.from(submittedKeys)}".`); | |
} | |
const key = params.get(validParamKey); | |
if (key === null) { | |
throw new Error(`Value was null. Please submit a valid value.`); | |
} | |
return key; | |
}; | |
const res = (status: number, body: Record<string, string> | string) => | |
new Response(JSON.stringify(body) ?? "{}", { status, headers: { "content-type": "text/json" } }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment