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