Files
mach_examples/05_todo_sse_datastar/main.c
2026-05-20 18:24:56 -05:00

117 lines
2.7 KiB
C

#include <mach.h>
#include <sqlite.h>
#include <datastar.h>
#include <session_auth.h>
string const create_todos_table = (asset){
#embed "create_todos_table.sql"
};
string const get_todos = (asset){
#embed "get_todos.sql"
};
string const create_todo = (asset){
#embed "create_todo.sql"
};
string const update_todo = (asset){
#embed "update_todo.sql"
};
string const delete_todo = (asset){
#embed "delete_todo.sql"
};
string const layout = (asset){
#embed "layout.mustache.html"
};
string const home = (asset){
#embed "home.mustache.html"
};
string const about = (asset){
#embed "about.mustache.html"
};
string const contact = (asset){
#embed "contact.mustache.html"
};
string const todos = (asset){
#embed "todos.mustache.html"
};
string const todo = (asset){
#embed "todo.mustache.html"
};
string const todo_item = (asset){
#embed "todo_item.mustache.html"
};
string const e5xx = (asset){
#embed "5xx.mustache.html"
};
string const e404 = (asset){
#embed "404.mustache.html"
};
void mach(){
middleware(session());
resource("home", "/",
.get = {mustache("home")}
);
resource("about", "/about",
.get = {mustache("about")}
);
resource("contact", "/contact",
.get = {mustache("contact")}
);
resource("todos", "/todos",
.all = {logged_in()},
.sse = {"todos:{{user_id}}"},
.get = {
sqlite_query({"todos_db", get_todos, "todos_data"}),
mustache("todos")
},
.post = {
input({"title", m_not_empty}),
sqlite_query({"todos_db", create_todo, "todo_data", .must_exist = true}),
datastar_sse("todos:{{user_id}}", .target = "todos", .mode = mode_prepend, .elements = {"todo"})
}
);
resource("todo", "/todos/:id",
.all = {
logged_in(),
input({"id", m_positive})
},
.patch = {
input({"finished", "1", "must be 1", .optional = true}),
sqlite_query({"todos_db", update_todo, "todo_data", .must_exist = true}),
datastar_sse("todos:{{user_id}}", .target = "todo_{{id}}", .mode = mode_replace, .elements = {"todo"})
},
.delete = {
sqlite_query({"todos_db", delete_todo, .must_exist = true}),
datastar_sse("todos:{{user_id}}", .target = "todo_{{id}}", .mode = mode_remove)
}
);
sqlite_database(
.name = "todos_db",
.connect = "file:todo.db?mode=rwc",
.migrations = {create_todos_table}
);
error(m_error, {mustache("5xx")});
error(m_not_found, {mustache("404")});
context("layout", layout);
context("home", home);
context("about", about);
context("contact", contact);
context("todos", todos);
context("todo", todo);
context("todo_item", todo_item);
context("5xx", e5xx);
context("404", e404);
module(sqlite);
module(datastar);
module(session_auth);
}