cargo loco generate scaffold bundle name:string^ description:text --htmx
This commit is contained in:
parent
f95a305f41
commit
d9a6cf8756
18 changed files with 434 additions and 3 deletions
54
nixin_farm_ssr/assets/views/bundle/create.html
Normal file
54
nixin_farm_ssr/assets/views/bundle/create.html
Normal file
|
@ -0,0 +1,54 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
Create bundle
|
||||
{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="mb-10">
|
||||
<form hx-post="/bundles" hx-ext="submitjson">
|
||||
<h1>Create new bundle</h1>
|
||||
<div class="mb-5">
|
||||
<div>
|
||||
<label>name</label>
|
||||
<br />
|
||||
<input id="name" name="name" type="text" value="" required/>
|
||||
</div>
|
||||
<div>
|
||||
<label>description</label>
|
||||
<br />
|
||||
<textarea id="description" name="description" type="text" value="" rows="10" cols="50"></textarea>
|
||||
</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 %}
|
73
nixin_farm_ssr/assets/views/bundle/edit.html
Normal file
73
nixin_farm_ssr/assets/views/bundle/edit.html
Normal file
|
@ -0,0 +1,73 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
Edit bundle: {{ item.id }}
|
||||
{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Edit bundle: {{ item.id }}</h1>
|
||||
<div class="mb-10">
|
||||
<form hx-post="/bundles/{{ 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}}" required></input>
|
||||
</div>
|
||||
<div>
|
||||
<label>description</label>
|
||||
<br />
|
||||
<textarea id="description" name="description" type="text">{{item.description}}</textarea>
|
||||
</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="/bundles">Back to bundle</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", "/bundles/{{ item.id }}", true);
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState == 4 && xhr.status == 200) {
|
||||
window.location.href = "/bundles";
|
||||
}
|
||||
};
|
||||
xhr.send();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
{% endblock js %}
|
27
nixin_farm_ssr/assets/views/bundle/list.html
Normal file
27
nixin_farm_ssr/assets/views/bundle/list.html
Normal file
|
@ -0,0 +1,27 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
List of bundle
|
||||
{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<h1>bundle</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>{{"description" | capitalize }}:</b> {{item.description}}</label>
|
||||
</div>
|
||||
<a href="/bundles/{{ item.id }}/edit">Edit</a>
|
||||
<a href="/bundles/{{ item.id }}">View</a>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<br />
|
||||
<br />
|
||||
<a href="/bundles/new">New bundle</a>
|
||||
</div>
|
||||
{% endblock content %}
|
19
nixin_farm_ssr/assets/views/bundle/show.html
Normal file
19
nixin_farm_ssr/assets/views/bundle/show.html
Normal file
|
@ -0,0 +1,19 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}
|
||||
View bundle: {{ item.id }}
|
||||
{% endblock title %}
|
||||
|
||||
{% block content %}
|
||||
<h1>View bundle: {{ item.id }}</h1>
|
||||
<div class="mb-10">
|
||||
<div>
|
||||
<label><b>{{"name" | capitalize }}:</b> {{item.name}}</label>
|
||||
</div>
|
||||
<div>
|
||||
<label><b>{{"description" | capitalize }}:</b> {{item.description}}</label>
|
||||
</div>
|
||||
<br />
|
||||
<a href="/bundles">Back to bundles</a>
|
||||
</div>
|
||||
{% endblock content %}
|
|
@ -6,6 +6,7 @@ mod m20220101_000001_users;
|
|||
mod m20231103_114510_notes;
|
||||
|
||||
mod m20241016_181828_servers;
|
||||
mod m20241021_121449_bundles;
|
||||
pub struct Migrator;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
|
@ -15,6 +16,7 @@ impl MigratorTrait for Migrator {
|
|||
Box::new(m20220101_000001_users::Migration),
|
||||
Box::new(m20231103_114510_notes::Migration),
|
||||
Box::new(m20241016_181828_servers::Migration),
|
||||
Box::new(m20241021_121449_bundles::Migration),
|
||||
]
|
||||
}
|
||||
}
|
37
nixin_farm_ssr/migration/src/m20241021_121449_bundles.rs
Normal file
37
nixin_farm_ssr/migration/src/m20241021_121449_bundles.rs
Normal 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(Bundles::Table)
|
||||
.col(pk_auto(Bundles::Id))
|
||||
.col(string_uniq(Bundles::Name))
|
||||
.col(text_null(Bundles::Description))
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(Bundles::Table).to_owned())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum Bundles {
|
||||
Table,
|
||||
Id,
|
||||
Name,
|
||||
Description,
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -50,6 +50,7 @@ impl Hooks for App {
|
|||
|
||||
fn routes(_ctx: &AppContext) -> AppRoutes {
|
||||
AppRoutes::with_default_routes()
|
||||
.add_route(controllers::bundle::routes())
|
||||
.add_route(controllers::server::routes())
|
||||
.add_route(controllers::notes::routes())
|
||||
.add_route(controllers::auth::routes())
|
||||
|
|
115
nixin_farm_ssr/src/controllers/bundle.rs
Normal file
115
nixin_farm_ssr/src/controllers/bundle.rs
Normal 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::bundles::{ActiveModel, Column, Entity, Model},
|
||||
views,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Params {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
impl Params {
|
||||
fn update(&self, item: &mut ActiveModel) {
|
||||
item.name = Set(self.name.clone());
|
||||
item.description = Set(self.description.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::bundle::list(&v, &item)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
pub async fn new(
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(_ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
views::bundle::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::bundle::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::bundle::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::bundle::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("bundles/")
|
||||
.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))
|
||||
}
|
|
@ -2,4 +2,5 @@ pub mod auth;
|
|||
pub mod notes;
|
||||
pub mod user;
|
||||
|
||||
pub mod server;
|
||||
pub mod server;
|
||||
pub mod bundle;
|
20
nixin_farm_ssr/src/models/_entities/bundles.rs
Normal file
20
nixin_farm_ssr/src/models/_entities/bundles.rs
Normal file
|
@ -0,0 +1,20 @@
|
|||
//! `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 = "bundles")]
|
||||
pub struct Model {
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
#[sea_orm(unique)]
|
||||
pub name: String,
|
||||
#[sea_orm(column_type = "Text", nullable)]
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
pub mod prelude;
|
||||
|
||||
pub mod bundles;
|
||||
pub mod notes;
|
||||
pub mod servers;
|
||||
pub mod users;
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
|
||||
|
||||
pub use super::bundles::Entity as Bundles;
|
||||
pub use super::notes::Entity as Notes;
|
||||
pub use super::servers::Entity as Servers;
|
||||
pub use super::users::Entity as Users;
|
||||
|
|
7
nixin_farm_ssr/src/models/bundles.rs
Normal file
7
nixin_farm_ssr/src/models/bundles.rs
Normal file
|
@ -0,0 +1,7 @@
|
|||
use sea_orm::entity::prelude::*;
|
||||
use super::_entities::bundles::{ActiveModel, Entity};
|
||||
pub type Bundles = Entity;
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
// extend activemodel below (keep comment for generators)
|
||||
}
|
|
@ -2,3 +2,4 @@ pub mod _entities;
|
|||
pub mod notes;
|
||||
pub mod users;
|
||||
pub mod servers;
|
||||
pub mod bundles;
|
||||
|
|
39
nixin_farm_ssr/src/views/bundle.rs
Normal file
39
nixin_farm_ssr/src/views/bundle.rs
Normal file
|
@ -0,0 +1,39 @@
|
|||
use loco_rs::prelude::*;
|
||||
|
||||
use crate::models::_entities::bundles;
|
||||
|
||||
/// Render a list view of bundles.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn list(v: &impl ViewRenderer, items: &Vec<bundles::Model>) -> Result<Response> {
|
||||
format::render().view(v, "bundle/list.html", data!({"items": items}))
|
||||
}
|
||||
|
||||
/// Render a single bundle view.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn show(v: &impl ViewRenderer, item: &bundles::Model) -> Result<Response> {
|
||||
format::render().view(v, "bundle/show.html", data!({"item": item}))
|
||||
}
|
||||
|
||||
/// Render a bundle create form.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn create(v: &impl ViewRenderer) -> Result<Response> {
|
||||
format::render().view(v, "bundle/create.html", data!({}))
|
||||
}
|
||||
|
||||
/// Render a bundle edit form.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When there is an issue with rendering the view.
|
||||
pub fn edit(v: &impl ViewRenderer, item: &bundles::Model) -> Result<Response> {
|
||||
format::render().view(v, "bundle/edit.html", data!({"item": item}))
|
||||
}
|
|
@ -1,4 +1,5 @@
|
|||
pub mod auth;
|
||||
pub mod user;
|
||||
|
||||
pub mod server;
|
||||
pub mod server;
|
||||
pub mod bundle;
|
31
nixin_farm_ssr/tests/models/bundles.rs
Normal file
31
nixin_farm_ssr/tests/models/bundles.rs
Normal file
|
@ -0,0 +1,31 @@
|
|||
use nixin_farm_ssr::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);
|
||||
}
|
|
@ -1,3 +1,4 @@
|
|||
mod users;
|
||||
|
||||
mod servers;
|
||||
mod servers;
|
||||
mod bundles;
|
Loading…
Reference in a new issue