cargagep-v2/src/api/helpers.rs
2026-08-24 11:09:59 +02:00

60 lines
1.8 KiB
Rust

use aide::transform::TransformResponse;
use schemars::JsonSchema;
use serde::Deserialize;
use axum::http::StatusCode;
use tracing::error;
use crate::core::{
controller::{AdminAppController, AppController, ControllerError, ManagerAppController},
models::unit::UnitId,
};
pub fn manager(
ac: AppController,
unit: Option<UnitId>,
) -> Result<ManagerAppController, (StatusCode, String)> {
ac.try_into_manager(unit).map_err(|_| {
(
StatusCode::FORBIDDEN,
"You are not allowed to act for this unit".to_owned(),
)
})
}
pub fn manager_desc<T>(op: TransformResponse<'_, T>) -> TransformResponse<'_, T> {
op.description("Forbidden - the user must be part of the unit, or an admin when the reservation names no known unit")
}
/// Narrows a session down to "admin", or 403
pub fn admin(ac: AppController) -> Result<AdminAppController, (StatusCode, String)> {
ac.try_into_admin().map_err(|_| {
(
StatusCode::FORBIDDEN,
"You are not allowed to perform this action".to_owned(),
)
})
}
pub fn admin_desc<T>(op: TransformResponse<'_, T>) -> TransformResponse<'_, T> {
op.description("Forbidden - the user must be an admin")
}
pub fn unexpected_error<T>(fn_name: &str, err: ControllerError) -> Result<T, (StatusCode, String)> {
error!("[HANDLER] {fn_name}: Unexpected error: {err:?}");
Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Unexpected error".to_owned(),
))
}
/// Shorthand to document a response: `.response_with::<404, (), _>(desc("..."))`
pub fn desc<T>(
description: &str,
) -> impl FnOnce(TransformResponse<'_, T>) -> TransformResponse<'_, T> {
|op| op.description(description)
}
#[derive(Debug, Deserialize, JsonSchema)]
pub struct IdPath {
pub id: i32,
}