refactor: move bot api calls to submitpane

This commit is contained in:
Ilion Beyst 2022-03-06 16:37:11 +01:00
parent 47ec2c6721
commit bd5dd17eb9
2 changed files with 43 additions and 41 deletions

View file

@ -2,6 +2,8 @@
import { createEventDispatcher, onMount } from "svelte";
import Select from "svelte-select";
export let editSession;
let availableBots: object[] = [];
let selectedOpponent = undefined;
let botName: string | undefined = undefined;
@ -21,16 +23,48 @@
const dispatch = createEventDispatcher();
function submitBot() {
dispatch("submitBot", {
opponentName: selectedOpponent["name"],
async function submitBot() {
const opponentName = selectedOpponent["name"];
let response = await fetch("/api/submit_bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code: editSession.getDocument().getValue(),
opponent_name: opponentName,
}),
});
let responseData = await response.json();
if (response.ok) {
// object has a "match" key containing the match data
dispatch("matchCreated", responseData);
} else {
throw responseData;
}
}
function saveBot() {
dispatch("saveBot", {
botName: botName,
async function saveBot() {
let response = await fetch("/api/save_bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
bot_name: botName,
code: editSession.getDocument().getValue(),
}),
});
let responseData = await response.json();
if (response.ok) {
dispatch("botSaved", responseData);
} else {
throw responseData;
}
}
</script>

View file

@ -38,45 +38,13 @@
(editSession as any).on("change", debounce(saveCode, 2000));
}
async function submitBot(e: CustomEvent) {
console.log(e.detail);
let response = await fetch("/api/submit_bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
code: editSession.getDocument().getValue(),
opponent_name: e.detail["opponentName"],
}),
});
if (!response.ok) {
throw Error(response.statusText);
}
let responseData = await response.json();
let matchData = responseData["match"];
async function onMatchCreated(e: CustomEvent) {
const matchData = e.detail["match"];
matches.unshift(matchData);
matches = matches;
await selectMatch(matchData["id"]);
}
async function saveBot(e: CustomEvent) {
let response = await fetch("/api/save_bot", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
bot_name: e.detail["botName"],
code: editSession.getDocument().getValue(),
}),
});
}
async function selectMatch(matchId: string) {
selectedMatchId = matchId;
selectedMatchLog = null;
@ -183,7 +151,7 @@
{#if selectedMatchId}
<OutputPane matchLog={selectedMatchLog} />
{:else}
<SubmitPane on:submitBot={submitBot} on:saveBot={saveBot} />
<SubmitPane {editSession} on:matchCreated={onMatchCreated} />
{/if}
</div>
</div>