cargo loco generate scaffold server name:string domain:string --htmx

This commit is contained in:
Douze Bé 2024-10-16 20:11:34 +02:00
parent d53053228a
commit c170e2050a
21 changed files with 464 additions and 6 deletions

View file

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock title %}</title>
<script src="https://unpkg.com/htmx.org@2.0.0/dist/htmx.min.js"></script>
<script src="https://cdn.tailwindcss.com?plugins=forms,typography,aspect-ratio,line-clamp"></script>
{% block head %}
{% endblock head %}
</head>
<body class="prose p-10">
<div id="content">
{% block content %}
{% endblock content %}
</div>
{% block js %}
{% endblock js %}
</body>
</html>

View file

@ -0,0 +1,54 @@
{% extends "base.html" %}
{% block title %}
Create server
{% endblock title %}
{% block content %}
<div class="mb-10">
<form hx-post="/servers" hx-ext="submitjson">
<h1>Create new server</h1>
<div class="mb-5">
<div>
<label>name</label>
<br />
<input id="name" name="name" type="text" value=""/>
</div>
<div>
<label>domain</label>
<br />
<input id="domain" name="domain" type="text" value=""/>
</div>
</div>
<div>
<button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock content %}
{% block js %}
<script>
htmx.defineExtension('submitjson', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['Content-Type'] = "application/json"
}
},
encodeParameters: function (xhr, parameters, elt) {
const json = {};
for (const [key, value] of Object.entries(parameters)) {
const inputType = elt.querySelector(`[name=${key}]`).type;
if (inputType === 'number') {
json[key] = parseFloat(value);
} else if (inputType === 'checkbox') {
json[key] = elt.querySelector(`[name=${key}]`).checked;
} else {
json[key] = value;
}
}
return JSON.stringify(json);
}
})
</script>
{% endblock js %}

View file

@ -0,0 +1,73 @@
{% extends "base.html" %}
{% block title %}
Edit server: {{ item.id }}
{% endblock title %}
{% block content %}
<h1>Edit server: {{ item.id }}</h1>
<div class="mb-10">
<form hx-post="/servers/{{ item.id }}" hx-ext="submitjson" hx-target="#success-message">
<div class="mb-5">
<div>
<label>name</label>
<br />
<input id="name" name="name" type="text" value="{{item.name}}"></input>
</div>
<div>
<label>domain</label>
<br />
<input id="domain" name="domain" type="text" value="{{item.domain}}"></input>
</div>
<div>
<div class="mt-5">
<button class=" text-xs py-3 px-6 rounded-lg bg-gray-900 text-white" type="submit">Submit</button>
<button class="text-xs py-3 px-6 rounded-lg bg-red-600 text-white"
onclick="confirmDelete(event)">Delete</button>
</div>
</div>
</form>
<div id="success-message" class="mt-4"></div>
<br />
<a href="/servers">Back to server</a>
</div>
{% endblock content %}
{% block js %}
<script>
htmx.defineExtension('submitjson', {
onEvent: function (name, evt) {
if (name === "htmx:configRequest") {
evt.detail.headers['Content-Type'] = "application/json"
}
},
encodeParameters: function (xhr, parameters, elt) {
const json = {};
for (const [key, value] of Object.entries(parameters)) {
const inputType = elt.querySelector(`[name=${key}]`).type;
if (inputType === 'number') {
json[key] = parseFloat(value);
} else if (inputType === 'checkbox') {
json[key] = elt.querySelector(`[name=${key}]`).checked;
} else {
json[key] = value;
}
}
return JSON.stringify(json);
}
})
function confirmDelete(event) {
event.preventDefault();
if (confirm("Are you sure you want to delete this item?")) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "/servers/{{ item.id }}", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
window.location.href = "/servers";
}
};
xhr.send();
}
}
</script>
{% endblock js %}

View file

@ -0,0 +1,27 @@
{% extends "base.html" %}
{% block title %}
List of server
{% endblock title %}
{% block content %}
<h1>server</h1>
<div class="mb-10">
{% for item in items %}
<div class="mb-5">
<div>
<label><b>{{"name" | capitalize }}:</b> {{item.name}}</label>
</div>
<div>
<label><b>{{"domain" | capitalize }}:</b> {{item.domain}}</label>
</div>
<a href="/servers/{{ item.id }}/edit">Edit</a>
<a href="/servers/{{ item.id }}">View</a>
</div>
{% endfor %}
<br />
<br />
<a href="/servers/new">New server</a>
</div>
{% endblock content %}

View file

@ -0,0 +1,19 @@
{% extends "base.html" %}
{% block title %}
View server: {{ item.id }}
{% endblock title %}
{% block content %}
<h1>View server: {{ item.id }}</h1>
<div class="mb-10">
<div>
<label><b>{{"name" | capitalize }}:</b> {{item.name}}</label>
</div>
<div>
<label><b>{{"domain" | capitalize }}:</b> {{item.domain}}</label>
</div>
<br />
<a href="/servers">Back to servers</a>
</div>
{% endblock content %}

View file

@ -5,6 +5,7 @@ pub use sea_orm_migration::prelude::*;
mod m20220101_000001_users;
mod m20231103_114510_notes;
mod m20241016_180911_servers;
pub struct Migrator;
#[async_trait::async_trait]
@ -13,6 +14,7 @@ impl MigratorTrait for Migrator {
vec![
Box::new(m20220101_000001_users::Migration),
Box::new(m20231103_114510_notes::Migration),
Box::new(m20241016_180911_servers::Migration),
]
}
}
}

View file

@ -0,0 +1,37 @@
use loco_rs::schema::table_auto_tz;
use sea_orm_migration::{prelude::*, schema::*};
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.create_table(
table_auto_tz(Servers::Table)
.col(pk_auto(Servers::Id))
.col(string_null(Servers::Name))
.col(string_null(Servers::Domain))
.to_owned(),
)
.await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.drop_table(Table::drop().table(Servers::Table).to_owned())
.await
}
}
#[derive(DeriveIden)]
enum Servers {
Table,
Id,
Name,
Domain,
}

View file

@ -50,6 +50,7 @@ impl Hooks for App {
fn routes(_ctx: &AppContext) -> AppRoutes {
AppRoutes::with_default_routes()
.add_route(controllers::server::routes())
.add_route(controllers::notes::routes())
.add_route(controllers::auth::routes())
.add_route(controllers::user::routes())
@ -75,4 +76,4 @@ impl Hooks for App {
db::seed::<notes::ActiveModel>(db, &base.join("notes.yaml").display().to_string()).await?;
Ok(())
}
}
}

View file

@ -1,3 +1,5 @@
pub mod auth;
pub mod notes;
pub mod user;
pub mod server;

View file

@ -0,0 +1,115 @@
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::unnecessary_struct_initialization)]
#![allow(clippy::unused_async)]
use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use sea_orm::{sea_query::Order, QueryOrder};
use axum::debug_handler;
use crate::{
models::_entities::servers::{ActiveModel, Column, Entity, Model},
views,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Params {
pub name: Option<String>,
pub domain: Option<String>,
}
impl Params {
fn update(&self, item: &mut ActiveModel) {
item.name = Set(self.name.clone());
item.domain = Set(self.domain.clone());
}
}
async fn load_item(ctx: &AppContext, id: i32) -> Result<Model> {
let item = Entity::find_by_id(id).one(&ctx.db).await?;
item.ok_or_else(|| Error::NotFound)
}
#[debug_handler]
pub async fn list(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = Entity::find()
.order_by(Column::Id, Order::Desc)
.all(&ctx.db)
.await?;
views::server::list(&v, &item)
}
#[debug_handler]
pub async fn new(
ViewEngine(v): ViewEngine<TeraView>,
State(_ctx): State<AppContext>,
) -> Result<Response> {
views::server::create(&v)
}
#[debug_handler]
pub async fn update(
Path(id): Path<i32>,
State(ctx): State<AppContext>,
Json(params): Json<Params>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
let mut item = item.into_active_model();
params.update(&mut item);
let item = item.update(&ctx.db).await?;
format::json(item)
}
#[debug_handler]
pub async fn edit(
Path(id): Path<i32>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::server::edit(&v, &item)
}
#[debug_handler]
pub async fn show(
Path(id): Path<i32>,
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
) -> Result<Response> {
let item = load_item(&ctx, id).await?;
views::server::show(&v, &item)
}
#[debug_handler]
pub async fn add(
ViewEngine(v): ViewEngine<TeraView>,
State(ctx): State<AppContext>,
Json(params): Json<Params>,
) -> Result<Response> {
let mut item = ActiveModel {
..Default::default()
};
params.update(&mut item);
let item = item.insert(&ctx.db).await?;
views::server::show(&v, &item)
}
#[debug_handler]
pub async fn remove(Path(id): Path<i32>, State(ctx): State<AppContext>) -> Result<Response> {
load_item(&ctx, id).await?.delete(&ctx.db).await?;
format::empty()
}
pub fn routes() -> Routes {
Routes::new()
.prefix("servers/")
.add("/", get(list))
.add("/", post(add))
.add("new", get(new))
.add(":id", get(show))
.add(":id/edit", get(edit))
.add(":id", post(update))
.add(":id", delete(remove))
}

View file

@ -1,6 +1,7 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
pub mod prelude;
pub mod notes;
pub mod servers;
pub mod users;

View file

@ -1,4 +1,4 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

View file

@ -1,4 +1,5 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
pub use super::notes::Entity as Notes;
pub use super::servers::Entity as Servers;
pub use super::users::Entity as Users;

View file

@ -0,0 +1,18 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
#[sea_orm(table_name = "servers")]
pub struct Model {
pub created_at: DateTimeWithTimeZone,
pub updated_at: DateTimeWithTimeZone,
#[sea_orm(primary_key)]
pub id: i32,
pub name: Option<String>,
pub domain: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

View file

@ -1,4 +1,4 @@
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

View file

@ -1,3 +1,4 @@
pub mod _entities;
pub mod notes;
pub mod users;
pub mod servers;

View file

@ -0,0 +1,7 @@
use sea_orm::entity::prelude::*;
use super::_entities::servers::{ActiveModel, Entity};
pub type Servers = Entity;
impl ActiveModelBehavior for ActiveModel {
// extend activemodel below (keep comment for generators)
}

View file

@ -1,2 +1,4 @@
pub mod auth;
pub mod user;
pub mod server;

View file

@ -0,0 +1,39 @@
use loco_rs::prelude::*;
use crate::models::_entities::servers;
/// Render a list view of servers.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn list(v: &impl ViewRenderer, items: &Vec<servers::Model>) -> Result<Response> {
format::render().view(v, "server/list.html", data!({"items": items}))
}
/// Render a single server view.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn show(v: &impl ViewRenderer, item: &servers::Model) -> Result<Response> {
format::render().view(v, "server/show.html", data!({"item": item}))
}
/// Render a server create form.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn create(v: &impl ViewRenderer) -> Result<Response> {
format::render().view(v, "server/create.html", data!({}))
}
/// Render a server edit form.
///
/// # Errors
///
/// When there is an issue with rendering the view.
pub fn edit(v: &impl ViewRenderer, item: &servers::Model) -> Result<Response> {
format::render().view(v, "server/edit.html", data!({"item": item}))
}

View file

@ -1 +1,3 @@
mod users;
mod servers;

View file

@ -0,0 +1,31 @@
use nixin_farm::app::App;
use loco_rs::testing;
use serial_test::serial;
macro_rules! configure_insta {
($($expr:expr),*) => {
let mut settings = insta::Settings::clone_current();
settings.set_prepend_module_to_snapshot(false);
let _guard = settings.bind_to_scope();
};
}
#[tokio::test]
#[serial]
async fn test_model() {
configure_insta!();
let boot = testing::boot_test::<App>().await.unwrap();
testing::seed::<App>(&boot.app_context.db).await.unwrap();
// query your model, e.g.:
//
// let item = models::posts::Model::find_by_pid(
// &boot.app_context.db,
// "11111111-1111-1111-1111-111111111111",
// )
// .await;
// snapshot the result:
// assert_debug_snapshot!(item);
}