planetwars.dev/web/pw-server/src/routes/bots/index.svelte

72 lines
1.5 KiB
Svelte
Raw Normal View History

2021-12-30 23:40:37 +01:00
<script lang="ts" context="module">
2021-12-31 11:38:06 +01:00
import { get_session_token } from "$lib/auth";
2021-12-30 23:40:37 +01:00
2021-12-31 11:38:06 +01:00
/** @type {import('@sveltejs/kit').Load} */
export async function load({ params, fetch, session, stuff }) {
const token = get_session_token();
const res = await fetch("/api/bots/my_bots", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
2021-12-30 23:40:37 +01:00
2021-12-31 11:38:06 +01:00
if (res.ok) {
return {
props: {
bots: await res.json(),
},
};
}
2021-12-30 23:40:37 +01:00
2021-12-31 11:38:06 +01:00
return {
status: res.status,
error: new Error("Could not load bots"),
};
}
2021-12-30 23:40:37 +01:00
</script>
<script lang="ts">
2021-12-31 11:38:06 +01:00
import { goto } from "$app/navigation";
2021-12-30 23:40:37 +01:00
2021-12-31 11:38:06 +01:00
export let bots: object[];
let name: string | undefined;
2021-12-30 23:40:37 +01:00
2021-12-31 11:38:06 +01:00
async function createBot() {
const token = get_session_token();
const res = await fetch("/api/bots", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
name: name,
}),
});
2021-12-30 23:40:37 +01:00
2021-12-31 11:38:06 +01:00
if (res.ok) {
let bot = await res.json();
goto(`/bots/${bot["id"]}`);
} else {
new Error("creation failed");
}
}
2021-12-30 23:40:37 +01:00
</script>
<form on:submit|preventDefault={createBot}>
2021-12-31 11:38:06 +01:00
<label for="name">Name</label>
<input name="name" bind:value={name} />
<button type="submit">Create</button>
2021-12-30 23:40:37 +01:00
</form>
<ul>
2021-12-31 11:38:06 +01:00
{#each bots as bot}
<li>
<a target="_blank" href={`bots/${bot["id"]}`}>
{bot["name"]}
</a>
</li>
{/each}
2021-12-30 23:40:37 +01:00
</ul>