Skip to content

Instantly share code, notes, and snippets.

@kwhinnery
Last active June 14, 2023 20:26
Show Gist options
  • Save kwhinnery/f5af50fff381bf12f0bff3ada13f6aeb to your computer and use it in GitHub Desktop.
Save kwhinnery/f5af50fff381bf12f0bff3ada13f6aeb to your computer and use it in GitHub Desktop.
The beginnings of a link shortening service in Deno, using Deno KV and Oak. Live coded on 6/14 here - https://www.youtube.com/watch?v=XaZTGGnP6EU
const kv = await Deno.openKv();
export interface Link {
slug: string;
destination: string;
}
export async function getLink(
slug: string,
): Promise<Link | null> {
if (!slug) {
throw new Error("A slug is required!");
}
const res = await kv.get(["links", slug]);
if (res.value) {
const l: Link = res.value as Link;
return l;
} else {
return null;
}
}
export async function createLink(
slug: string,
destination: string,
): Promise<Link> {
if (!slug || !destination) {
throw new Error("A slug and destination are required!");
}
const key = ["links", slug];
const value: Link = {
slug,
destination,
};
const res = await kv.atomic()
.check({ key, versionstamp: null })
.set(key, value)
.commit();
if (res.ok) {
return value;
} else {
throw new Error("Could not create link!");
}
}
import { Application, Router } from "https://deno.land/x/oak@v12.5.0/mod.ts";
import { createLink, getLink, Link } from "./db.ts";
const app = new Application();
const api = new Router();
api.get("/:slug", async (ctx) => {
const l: Link = await getLink(ctx.params.slug);
console.log(ctx.params.slug);
ctx.response.body = JSON.stringify(l);
});
api.post("/create", async (ctx) => {
const input = await ctx.request.body({
type: "json",
});
const jsonInput: any = await input.value;
const newLink: Link = await createLink(jsonInput.slug, jsonInput.destination);
ctx.response.body = newLink;
});
app.use(api.routes());
app.use(api.allowedMethods());
await app.listen({ port: 8000 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment