aboutsummaryrefslogtreecommitdiff
path: root/client/src/lib/actions
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/lib/actions')
-rw-r--r--client/src/lib/actions/shorten.ts50
1 files changed, 50 insertions, 0 deletions
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<ShortenResponse>;
+}
+
+async function makeRequest(url: string): Promise<ShortenResponse> {
+ 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),
+ };
+}