Adds hit route

This commit is contained in:
2025-10-05 20:35:23 +02:00
parent 37a83275bd
commit f45900d69d
5 changed files with 80 additions and 0 deletions

75
src/api/hit.rs Normal file
View File

@@ -0,0 +1,75 @@
use crate::dtos::hit::HitDTO;
use crate::models::AppState;
use crate::models::hit::Hit;
use crate::schema::hits;
use crate::schema::hits::dsl;
use diesel::ExpressionMethods;
use diesel::{QueryDsl, RunQueryDsl, SelectableHelper};
use rocket::State;
use rocket::http::Status;
use rocket::serde::json::Json;
use uuid::Uuid;
#[get("/?<offset>&<limit>")]
pub fn index(
offset: Option<i64>,
limit: Option<i64>,
state: &State<AppState>,
) -> Result<Json<Vec<HitDTO>>, Status> {
let mut db = state.db.lock().unwrap();
let offset = offset.unwrap_or(0);
let limit = limit.unwrap_or(10);
let results = dsl::hits
.offset(offset)
.limit(limit)
.select(Hit::as_select())
.load(&mut *db)
.ok();
match results {
Some(results) => Ok(Json(results.iter().map(HitDTO::from).collect())),
None => Err(Status::InternalServerError),
}
}
#[get("/<id>")]
pub fn get(id: String, state: &State<AppState>) -> Result<Json<HitDTO>, Status> {
let mut db = state.db.lock().unwrap();
let id = match Uuid::parse_str(id.as_str()).ok() {
Some(id) => id,
None => return Err(Status::BadRequest),
};
let result = dsl::hits
.filter(hits::id.eq(id))
.first::<Hit>(&mut *db)
.ok();
match result {
Some(tracker) => Ok(Json(HitDTO::from(&tracker))),
None => Err(Status::NotFound),
}
}
#[delete("/<id>")]
pub fn delete(id: String, state: &State<AppState>) -> Result<Status, Status> {
let mut db = state.db.lock().unwrap();
let id = match Uuid::parse_str(id.as_str()).ok() {
Some(id) => id,
None => return Err(Status::BadRequest),
};
let count = diesel::delete(dsl::hits.filter(dsl::id.eq(id)))
.execute(&mut *db)
.ok();
match count {
Some(count) if count > 0 => Ok(Status::Ok),
Some(_) => Ok(Status::NotFound),
None => Err(Status::InternalServerError),
}
}

View File

@@ -1 +1,2 @@
pub mod tracker; pub mod tracker;
pub mod hit;

View File

@@ -87,6 +87,8 @@ pub fn delete(id: String, state: &State<AppState>) -> Result<Status, Status> {
.execute(&mut *db) .execute(&mut *db)
.ok(); .ok();
// TODO: maybe delete all associated hits?
match count { match count {
Some(count) if count > 0 => Ok(Status::Ok), Some(count) if count > 0 => Ok(Status::Ok),
Some(_) => Ok(Status::NotFound), Some(_) => Ok(Status::NotFound),

View File

@@ -3,6 +3,7 @@ mod dtos;
mod models; mod models;
mod schema; mod schema;
use crate::api::hit;
use crate::api::tracker; use crate::api::tracker;
use diesel::{Connection, PgConnection}; use diesel::{Connection, PgConnection};
use std::env; use std::env;
@@ -36,4 +37,5 @@ fn rocket() -> _ {
tracker::delete tracker::delete
], ],
) )
.mount("/hit", routes![hit::index, hit::get, hit::delete])
} }

BIN
static/image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 B