Files
snooze-pal/src/resources/alarm/post.rs

76 lines
1.5 KiB
Rust

use axum::extract::State;
use axum::{Json};
use axum::http::StatusCode;
use axum::debug_handler;
use axum::response::IntoResponse;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::{IntoResponses, ToSchema};
use crate::AppState;
use crate::types::Alarm;
#[derive(Debug, Deserialize, ToSchema)]
pub struct RequestBody {
title: String,
time: DateTime<Utc>,
}
#[derive(ToSchema, Serialize)]
pub struct OkResponseBody {
id: i32,
time: DateTime<Utc>,
title: String,
enabled: bool,
}
#[derive(IntoResponses)]
pub enum Responses {
#[response(status = 200)]
Ok(#[to_schema] OkResponseBody),
#[response(status = 500)]
Error(String)
}
impl IntoResponse for Responses {
fn into_response(self) -> axum::response::Response {
match self {
Responses::Ok(body) => (StatusCode::OK, Json(body)).into_response(),
Responses::Error(message) => (StatusCode::INTERNAL_SERVER_ERROR, Json(message)).into_response(),
}
}
}
impl From<Alarm> for OkResponseBody {
fn from(value: Alarm) -> Self {
OkResponseBody {
time: value.time,
enabled: value.enabled,
title: value.title,
id: value.id
}
}
}
#[utoipa::path(
post,
path = "",
responses(
Responses
)
)]
#[debug_handler]
pub async fn post_handler(State(AppState { scheduler, ..}): State<AppState>, Json(body): Json<RequestBody>) -> Responses {
let result = scheduler.add_alarm(body.time, body.title).await;
match result {
Ok(alarm) => {
Responses::Ok(alarm.into())
},
Err(e) => {
Responses::Error(e.to_string())
}
}
}