Add REST helpers and the customer model

This commit is contained in:
Paul van Tilburg 2019-06-20 20:04:05 +02:00
parent 344ca286da
commit f4d72b68d2
3 changed files with 59 additions and 1 deletions

View File

@ -8,8 +8,14 @@ use rocket::{catchers, routes, Rocket};
use rocket_contrib::database;
use rocket_contrib::serve::StaticFiles;
#[macro_use]
mod rest_helpers;
pub mod catchers;
pub mod handlers;
pub mod models;
/// The application database schema
pub mod schema;
#[database("stoptime_db")]
pub struct DbConn(diesel::SqliteConnection);

View File

@ -7,7 +7,7 @@ use crate::schema::customers;
///
/// This model represents a customer that has projects/tasks for which invoices need to be
/// generated.
#[derive(AsChangeset, Debug, Deserialize, Identifiable, Queryable, Serialize)]
#[derive(AsChangeset, Debug, Deserialize, Identifiable, PartialEq, Queryable, Serialize)]
#[table_name = "customers"]
pub struct Customer {
/// The unique identification number

52
src/rest_helpers.rs Normal file
View File

@ -0,0 +1,52 @@
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;
let table = $crate::models::$model_name::table();
let primary_key = table.primary_key();
$conn.transaction::<_, 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! delete {
($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),
}
}};
}