bake id into post request uri

This commit is contained in:
Zynh0722 2023-09-26 17:00:01 -07:00
parent 96dd76e463
commit ddbd2c330a
3 changed files with 13 additions and 25 deletions

View file

@ -1,5 +1,7 @@
use axum::extract::Path;
use axum::{extract::State, response::IntoResponse, routing::post}; use axum::{extract::State, response::IntoResponse, routing::post};
use cm_lib::models::Shift; use cm_lib::models::Shift;
use cm_lib::schema::shifts;
use diesel::{ExpressionMethods, OptionalExtension, QueryDsl, SelectableHelper}; use diesel::{ExpressionMethods, OptionalExtension, QueryDsl, SelectableHelper};
use diesel_async::{scoped_futures::ScopedFutureExt, AsyncConnection, RunQueryDsl}; use diesel_async::{scoped_futures::ScopedFutureExt, AsyncConnection, RunQueryDsl};
@ -9,7 +11,7 @@ use crate::AppState;
pub(crate) fn router() -> axum::Router<AppState> { pub(crate) fn router() -> axum::Router<AppState> {
axum::Router::new() axum::Router::new()
.route("/shifts/open", post(open_shift)) .route("/shifts/open", post(open_shift))
.route("/shifts/close", post(close_shift)) .route("/shifts/:id/close", post(close_shift))
} }
async fn open_shift(State(state): State<AppState>) -> impl IntoResponse { async fn open_shift(State(state): State<AppState>) -> impl IntoResponse {
@ -40,29 +42,13 @@ async fn open_shift(State(state): State<AppState>) -> impl IntoResponse {
render!(crate::templates::home_html, shift) render!(crate::templates::home_html, shift)
} }
async fn close_shift(State(state): State<AppState>) -> impl IntoResponse { async fn close_shift(State(state): State<AppState>, Path(id): Path<u32>) -> impl IntoResponse {
{ let mut conn = state.connection.get().await.unwrap();
let mut conn = state.connection.get().await.unwrap(); diesel::update(shifts::table.filter(shifts::id.eq(id)))
conn.transaction(|conn| { .set(shifts::end.eq(Some(chrono::Utc::now().naive_local())))
use cm_lib::schema::shifts::dsl::*; .execute(&mut conn)
async move {
let open_shift = shifts
.filter(end.is_null())
.select(Shift::as_select())
.first(conn)
.await?;
diesel::update(shifts.filter(id.eq(open_shift.id)))
.set(end.eq(Some(chrono::Utc::now().naive_local())))
.execute(conn)
.await
}
.scope_boxed()
})
.await .await
.unwrap(); .unwrap();
}
render!(crate::templates::home_html, None) render!(crate::templates::home_html, None)
} }

View file

@ -1,5 +1,7 @@
@() @use cm_lib::models::Shift;
<button hx-post="/api/shifts/close" hx-swap="outerHTML" type="button"> @(open_shift: Shift)
<button hx-post="/api/shifts/@open_shift.id/close" hx-swap="outerHTML" type="button">
Close Shift Close Shift
</button> </button>

View file

@ -12,7 +12,7 @@
@if open_shift.is_none() { @if open_shift.is_none() {
@:open_shift_button_html() @:open_shift_button_html()
} else { } else {
@:close_shift_button_html() @:close_shift_button_html(open_shift.unwrap())
} }
</div> </div>
</main> </main>