stoptime-rs/src/rest_helpers.rs

166 lines
5.0 KiB
Rust

//! Some REST API herlpers
//!
//! The macros, types and traits in this module are used to create a simple REST API on top of
//! models that are in the database.
#![allow(unused_macros)]
use diesel::result::{DatabaseErrorKind, Error as QueryError};
use rocket::http::Status;
use rocket::response::status::Created;
use rocket_contrib::json::Json;
use serde::Serialize;
/// Conversion into a Rocket [`Status`].
trait IntoStatus {
fn into_status(self) -> Status;
}
impl IntoStatus for QueryError {
fn into_status(self) -> Status {
match self {
QueryError::NotFound => Status::NotFound,
QueryError::DatabaseError(kind, _info) => match kind {
DatabaseErrorKind::UniqueViolation => Status::Conflict,
DatabaseErrorKind::ForeignKeyViolation => Status::BadRequest,
_ => Status::InternalServerError,
},
_ => Status::InternalServerError,
}
}
}
/// A specialized `Result` type for Rocket JSON reponses.
///
/// It contains either a JSON serialization or an (error) Rocket [`Status`].
pub type JsonResponse<T> = Result<Json<T>, Status>;
/// Conversion into a [`JsonResponse`].
pub trait IntoJsonResponse<T> {
fn into_json_response(self) -> JsonResponse<T>;
}
impl<T> IntoJsonResponse<T> for Result<T, QueryError> {
fn into_json_response(self) -> JsonResponse<T> {
self.map(|item| Json(item))
.map_err(|error| error.into_status())
}
}
impl<T> IntoJsonResponse<T> for T
where
T: Serialize,
{
fn into_json_response(self) -> JsonResponse<T> {
Ok(Json(self))
}
}
/// A specialized `Result` type for Rocket Created (with JSON) reponses.
///
/// It contains either a JSON serialization with URI in a [`Created`] struct or an (error) Rocket
/// [`Status`].
pub type CreatedJsonResponse<T> = Result<Created<Json<T>>, Status>;
/// Conversion into a [`CreatedJsonResponse`].
pub trait IntoCreatedJsonResponse<T> {
fn into_created_json_response<F>(self, uri_func: F) -> CreatedJsonResponse<T>
where
F: Fn(&T) -> String;
}
impl<T> IntoCreatedJsonResponse<T> for Result<T, QueryError> {
fn into_created_json_response<F>(self, uri_func: F) -> CreatedJsonResponse<T>
where
F: Fn(&T) -> String,
{
self.map(|item| Created(uri_func(&item), Some(Json(item))))
.map_err(|error| error.into_status())
}
}
/// A specialized `Result` type for Rocket `Status::NoContent` reponses.
///
/// It contains either a [`Status::NoContent`] in the Ok case, or an (error) Rocket [`Status`]
/// in the Err case.
pub type NoContentResponse = Result<Status, Status>;
/// Conversion into a [`NoContentResponse`].
pub trait IntoNoContentResponse {
fn into_no_content_response(self) -> NoContentResponse;
}
impl<T> IntoNoContentResponse for Result<T, QueryError> {
fn into_no_content_response(self) -> NoContentResponse {
self.map(|_item| Status::NoContent)
.map_err(|error| error.into_status())
}
}
macro_rules! all {
($model_name:ident, $conn:expr) => {{
use diesel::associations::HasTable;
let table = $crate::models::$model_name::table();
table.load(&$conn)
}};
}
macro_rules! get {
($model_name:ident, $primary_key:expr, $conn:expr) => {{
use diesel::associations::HasTable;
let table = $crate::models::$model_name::table();
table.find($primary_key).first(&$conn)
}};
}
macro_rules! create {
($model_name:ident, $object:expr, $conn:expr) => {{
use diesel::associations::HasTable;
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl, Table};
let table = $crate::models::$model_name::table();
let primary_key = table.primary_key();
$conn.transaction::<$model_name, diesel::result::Error, _>(|| {
diesel::insert_into(table).values($object).execute(&$conn)?;
table.order(primary_key.desc()).first(&$conn)
})
}};
}
macro_rules! update {
($model_name:ident, $primary_key:expr, $object:expr, $conn:expr) => {{
use diesel::associations::HasTable;
let table = $crate::models::$model_name::table();
$conn.transaction::<_, diesel::result::Error, _>(|| {
diesel::update(table.find($primary_key))
.set($object)
.execute(&$conn)?;
table.find($primary_key).first(&$conn)
})
}};
}
macro_rules! destroy {
($model_name:ident, $primary_key:expr, $conn:expr) => {{
use diesel::associations::HasTable;
let table = $crate::models::$model_name::table();
let result: Result<$model_name, _> = get!($model_name, $primary_key, $conn);
match result {
Ok(_) => diesel::delete(table.find($primary_key)).execute(&$conn),
Err(e) => Err(e),
}
}};
}
macro_rules! destroy_all {
($model_name:ident, $conn:expr) => {{
use diesel::associations::HasTable;
use diesel::RunQueryDsl;
let table = $crate::models::$model_name::table();
diesel::delete(table).execute(&$conn)
}};
}