From f3f50133973d423bc5544d84c789fba8636397cc Mon Sep 17 00:00:00 2001 From: Christopher Bisset Date: Tue, 12 Jul 2022 20:54:39 +1000 Subject: [PATCH] deduplicated get user code --- src/routes/index.svelte | 42 ++++++++++------------------------------- 1 file changed, 10 insertions(+), 32 deletions(-) diff --git a/src/routes/index.svelte b/src/routes/index.svelte index c96e554..14735ce 100644 --- a/src/routes/index.svelte +++ b/src/routes/index.svelte @@ -4,8 +4,7 @@ import UserCard from '$lib/index/UserCard.svelte'; import { onMount } from 'svelte'; import { fade } from 'svelte/transition'; - import { headscaleURLStore } from '$lib/common/stores.js'; - import { headscaleAPIKeyStore } from '$lib/common/stores.js'; + import { getUsers } from '$lib/common/apiFunctions.svelte'; // // Component Variables @@ -17,41 +16,20 @@ // page state variables let headscaleAPITest = 'untested'; - // endpoint url for getting users - let endpointURL = '/api/v1/namespace'; - // note that headscale API refers to users as namespaces still. This variable will hold our user's array let headscaleUsers = [{ id: '', name: '', createdAt: '' }]; - - function getUsers() { - fetch($headscaleURLStore + endpointURL, { - method: 'GET', - headers: { - Accept: 'application/json', - Authorization: `Bearer ${$headscaleAPIKeyStore}` - } - }) - .then((response) => { - if (response.ok) { - headscaleAPITest = 'succeeded'; - // return the api data - response.json().then((data) => { - headscaleUsers = data.namespaces; - }); - } else { - headscaleAPITest = 'failed'; - } - }) - .catch((error) => { - headscaleAPITest = 'failed'; - }); - } - // We define the meat of our script in onMount as doing so forces client side rendering. // Doing so also does not perform any actions until components are initialized onMount(async () => { - getUsers(); + getUsers() + .then((users) => { + headscaleUsers = users; + headscaleAPITest = 'succeeded'; + }) + .catch(() => { + headscaleAPITest = 'failed'; + }); // load the page componentLoaded = true; }); @@ -64,7 +42,7 @@ {#if headscaleAPITest === 'succeeded'} - getUsers()}/> + getUsers()} /> {#each headscaleUsers as user} getUsers()} {user} /> {/each}