Creation of a reminder via web api
Concurrently run the reminder service as well as an web endpoint to create a new reminder. Note that a new reminder does not notify the reminder service yet. Cargo update dependencies
This commit is contained in:
parent
6b6f5aa48a
commit
7ded3ef430
5 changed files with 123 additions and 56 deletions
69
src/api.rs
Normal file
69
src/api.rs
Normal file
|
@ -0,0 +1,69 @@
|
|||
use crate::{schema, NewReminder};
|
||||
use anyhow::Error;
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response, Result},
|
||||
Json,
|
||||
};
|
||||
use diesel::{
|
||||
prelude::*,
|
||||
r2d2::{ConnectionManager, Pool},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use time::OffsetDateTime;
|
||||
use tracing::{error, trace};
|
||||
|
||||
pub struct ServerError(Error);
|
||||
|
||||
impl IntoResponse for ServerError {
|
||||
fn into_response(self) -> Response {
|
||||
error!("{}", self.0);
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong.").into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> From<E> for ServerError
|
||||
where
|
||||
E: Into<Error>,
|
||||
{
|
||||
fn from(err: E) -> Self {
|
||||
Self(err.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateReminder {
|
||||
#[serde(with = "time::serde::iso8601")]
|
||||
planned: OffsetDateTime,
|
||||
title: String,
|
||||
message: String,
|
||||
receiver: String,
|
||||
}
|
||||
|
||||
#[allow(clippy::unused_async)]
|
||||
pub async fn create_reminder(
|
||||
State(db_pool): State<Pool<ConnectionManager<PgConnection>>>,
|
||||
Json(data): Json<CreateReminder>,
|
||||
) -> Result<impl IntoResponse, ServerError> {
|
||||
let reminder = NewReminder {
|
||||
created: OffsetDateTime::now_utc(),
|
||||
planned: data.planned,
|
||||
title: &data.title,
|
||||
message: &data.message,
|
||||
receiver: &data.receiver,
|
||||
};
|
||||
|
||||
trace!(?data, "received data");
|
||||
|
||||
diesel::insert_into(schema::reminders::table)
|
||||
.values(&reminder)
|
||||
.execute(&mut db_pool.get()?)?;
|
||||
|
||||
Ok((StatusCode::CREATED, "Reminder created".to_string()))
|
||||
}
|
||||
|
||||
#[allow(clippy::unused_async)]
|
||||
pub async fn not_found() -> impl IntoResponse {
|
||||
(StatusCode::NOT_FOUND, "Page not found")
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue