From 42860fa15985401825d8d51e73ec497fe5876710 Mon Sep 17 00:00:00 2001 From: Melonai Date: Wed, 24 Mar 2021 09:51:36 +0100 Subject: Update SvelteKit to public beta --- client/src/lib/actions/shorten.ts | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 client/src/lib/actions/shorten.ts (limited to 'client/src/lib/actions') diff --git a/client/src/lib/actions/shorten.ts b/client/src/lib/actions/shorten.ts new file mode 100644 index 0000000..ca685c5 --- /dev/null +++ b/client/src/lib/actions/shorten.ts @@ -0,0 +1,50 @@ +interface ShortenResponse { + hash: string; +} + +export interface ShortenRequest { + url: string; + nonce: string; + response: Promise; +} + +async function makeRequest(url: string): Promise { + let body; + + try { + const response = await fetch("/", { + headers: { + Accept: "application/json", + "Content-Type": "application/json", + }, + method: "post", + body: JSON.stringify({ url }), + }); + + body = await response.json(); + } catch (err) { + throw { + error: "Error!", + }; + } + + if (body.hash) { + return { + hash: body.hash, + }; + } else { + throw { + message: body.error || "Error!", + }; + } +} + +export default function shorten(url: string): ShortenRequest { + const nonce = Math.random().toString(36).substr(2, 5); + + return { + url, + nonce, + response: makeRequest(url), + }; +} -- cgit 1.4.1