diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..0c0ea44 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "deno.enable": true, + "deno.unstable": true, +} diff --git a/routes/index.tsx b/routes/index.tsx index f56e433..f64e858 100644 --- a/routes/index.tsx +++ b/routes/index.tsx @@ -7,7 +7,7 @@ type HandlerResponse = { url?: string; isUpdated?: boolean; error?: string; -} +}; export const handler: Handlers = { async POST(req, ctx) { @@ -17,18 +17,25 @@ export const handler: Handlers = { case "PUT": { const originalUrl = form.get("original_url") as string; const customUrl = form.get("custom_url") as string; - const customised = await customiseShortenedUrl(originalUrl, customUrl); - return ctx.render({ - url: customised, - isUpdated: true, - }); + try { + const customised = await customiseShortenedUrl( + originalUrl, + customUrl, + ); + return ctx.render({ + url: customised, + isUpdated: true, + }); + } catch { + return ctx.render({ error: "Customised url already exists" }); + } } default: { const originalUrl = form.get("url") as string; if (!originalUrl) return ctx.render({ error: "URL cannot be empty" }); const shortened = await shortenUrl(originalUrl); return ctx.render({ - url: shortened + url: shortened, }); } } @@ -38,11 +45,7 @@ export const handler: Handlers = { export default function Home(props: PageProps) { return (
- WRI Logo + WRI Logo
(originalKey); const customisedKey = ["url", customised]; + + // check if customised already exists + if (await kv.get(customisedKey)) { + throw new Error("Customised url already exists"); + } + await kv .atomic() .check(originalShortened) .check({ key: customisedKey, versionstamp: null }) .delete(originalKey) - .set(customisedKey, originalShortened.value as string, { expireIn: KEY_EXPIRY }) + .set(customisedKey, originalShortened.value as string) .commit(); return customised; } @@ -34,4 +39,4 @@ export async function resolveUrl(token: string): Promise { const url = await kv.get(key); if (!url) return null; return url.value as string; -} \ No newline at end of file +}