From 826c7c47785ee01d2b9267919132ada696425344 Mon Sep 17 00:00:00 2001 From: Melonai Date: Wed, 20 Jan 2021 23:18:09 +0100 Subject: Remade the client in SvelteKit --- client/src/actions/shorten.ts | 50 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 client/src/actions/shorten.ts (limited to 'client/src/actions/shorten.ts') diff --git a/client/src/actions/shorten.ts b/client/src/actions/shorten.ts new file mode 100644 index 0000000..58dd4f0 --- /dev/null +++ b/client/src/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("http://localhost:4000/", { + 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