Skip to content

Commit e7d5fcd

Browse files
author
Mike Nikles
committed
Add GET and POST endpoints.
1 parent e2409c5 commit e7d5fcd

File tree

4 files changed

+64
-6
lines changed

4 files changed

+64
-6
lines changed

src/global.d.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,7 @@
11
/// <reference types="@sveltejs/kit" />
2+
3+
type Todo = {
4+
created_at: Date;
5+
text: string;
6+
done: boolean;
7+
}

src/lib/todo-item.svelte

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
<script lang="ts">
2+
export let todo: Todo;
3+
</script>
4+
15
<style>
26
.todo {
37
display: grid;
@@ -85,7 +89,7 @@
8589
</form>
8690

8791
<form action="" method="" class="text">
88-
<input type="text" />
92+
<input type="text" value="{todo.text}" />
8993
<button aria-label="Save todo" class="save"></button>
9094
</form>
9195

src/routes/index.svelte

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,28 @@
1-
<script>
1+
<script context="module" lang="ts">
2+
import type { Load } from "@sveltejs/kit";
3+
4+
export const load: Load = async ({ fetch }) => {
5+
const res = await fetch("/todos.json");
6+
7+
if (res.ok) {
8+
const todos = await res.json();
9+
return {
10+
props: { todos }
11+
}
12+
}
13+
14+
const { message } = await res.json();
15+
return {
16+
error: new Error(message)
17+
}
18+
};
19+
</script>
20+
21+
<script lang="ts">
222
import TodoItem from "$lib/todo-item.svelte";
323
24+
export let todos: Todo[];
25+
426
const title = "Todo";
527
</script>
628

@@ -43,11 +65,11 @@
4365
<div class="todos">
4466
<h1>{title}</h1>
4567

46-
<form action="" method="" class="new">
68+
<form action="/todos.json" method="post" class="new">
4769
<input type="text" name="text" aria-label="Add a todo" placeholder="+ type to add a todo" />
4870
</form>
4971

50-
<TodoItem />
51-
<TodoItem />
52-
<TodoItem />
72+
{#each todos as todo}
73+
<TodoItem {todo} />
74+
{/each}
5375
</div>

src/routes/todos/index.json.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { RequestHandler } from "@sveltejs/kit";
2+
3+
// TODO: Persist in database
4+
let todos: Todo[] = [];
5+
6+
export const get: RequestHandler = () => {
7+
return {
8+
status: 200,
9+
body: todos
10+
}
11+
}
12+
13+
export const post: RequestHandler<{}, FormData> = (request) => {
14+
todos.push({
15+
created_at: new Date(),
16+
text: request.body.get("text"),
17+
done: false
18+
});
19+
20+
return {
21+
status: 303,
22+
headers: {
23+
location: "/"
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)