Skip to content

Instantly share code, notes, and snippets.

@sbmsr
Created July 29, 2024 19:05
Show Gist options
  • Save sbmsr/e83b4436713478830518e25156b8ee0d to your computer and use it in GitHub Desktop.
Save sbmsr/e83b4436713478830518e25156b8ee0d to your computer and use it in GitHub Desktop.
recurse db server
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