Accept is way too complicated, so I'll have to investigate other ways this is done.

main
Zed A. Shaw 9 months ago
parent 825378c2b6
commit b38b14e2f6
  1. 15
      controllers/todo_alpine.js
  2. 29
      templates/todo_alpine.html

@ -1,21 +1,15 @@
import { ToDo } from "../lib/models.js"; import { ToDo } from "../lib/models.js";
import nunjucks from "nunjucks"; import nunjucks from "nunjucks";
// this can go away when I learn how to detect the request type export class Todo {
export class TodoIndex {
async get(req, rep) { async get(req, rep) {
if(req.headers.accept === "application/json") {
const todo_list = await ToDo.all({}); const todo_list = await ToDo.all({});
rep.code(200).send(todo_list);
} else {
const result = nunjucks.render("todo_alpine.html", {name: "Zed"}); const result = nunjucks.render("todo_alpine.html", {name: "Zed"});
rep.code(200).type("text/html").send(result); rep.code(200).type("text/html").send(result);
} }
}
export class Todo {
async get(req, rep) {
const todo_list = await ToDo.all({});
rep.code(200).send(todo_list);
} }
async post(req, rep) { async post(req, rep) {
@ -33,5 +27,4 @@ export class Todo {
// I mean, it works not sure if I like it though // I mean, it works not sure if I like it though
export default { export default {
todo_alpine: Todo, todo_alpine: Todo,
todo_index: TodoIndex
}; };

@ -5,8 +5,29 @@
<script> <script>
const new_task = async (todos, task) => { const new_task = async (todos, task) => {
const result = await axios({
method: "post",
url: "/todo_alpine",
data: {task},
headers: {
Accept: "application/json"
}
});
// zero error handling but fine for now // zero error handling but fine for now
return (await axios.post("/todo_alpine", {task})).data; return result.data;
}
const list_todo = async () => {
const result = await axios({
method: "get",
url: "/todo_alpine",
headers: {
Accept: "application/json"
}
});
return result.data;
} }
</script> </script>
@ -14,7 +35,7 @@
<div <div
x-data="{todos: []}" x-data="{todos: []}"
x-init="todos = (await axios.get('/todo_alpine')).data"> x-init="todos = await list_todo()">
<ol> <ol>
<template x-for="todo of todos"> <template x-for="todo of todos">
<li x-text="todo.task"></li> <li x-text="todo.task"></li>
@ -22,10 +43,10 @@
</ol> </ol>
<h4>Add a New TODO</h4> <h4>Add a New TODO</h4>
<form action="/todo_index" @submit.prevent="todos = new_task(todos, task), task = ''" method="POST" x-data="{task: ''}"> <form action="/todo_alpine" @submit.prevent="todos = await new_task(todos, task), task = ''" method="POST" x-data="{task: ''}">
<label for="task">Task</label> <label for="task">Task</label>
<input name="task" x-model="task"></input> <input name="task" x-model="task"></input>
<button type="button" @click="todos = new_task(todos, task), task = ''">Submit</button> <button type="button" @click="todos = await new_task(todos, task), task = ''">Submit</button>
</form> </form>
</div> </div>

Loading…
Cancel
Save