Add vote_exists and additional delete/get vote count handler
This commit is contained in:
parent
f81b29c5e9
commit
c77e58f21b
4 changed files with 90 additions and 10 deletions
|
|
@ -1,17 +1,26 @@
|
|||
use axum::{
|
||||
Router,
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
routing::post,
|
||||
routing::{delete, get, post},
|
||||
};
|
||||
use axum_extra::extract::{CookieJar, cookie::Cookie};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{state::AppState, votes::repository::insert_new_vote};
|
||||
use crate::{
|
||||
state::AppState,
|
||||
votes::{
|
||||
repository::{delete_vote, insert_new_vote},
|
||||
service::get_votes_and_voted,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new().route("/posts/{slug}/vote", post(upvote_handler))
|
||||
Router::new()
|
||||
.route("/posts/{slug}/vote", post(upvote_handler))
|
||||
.route("/posts/{slug}/vote", delete(downvote_handler))
|
||||
.route("/posts/{slug}/votes", get(get_votes_and_voted_handler))
|
||||
}
|
||||
|
||||
fn get_or_init_voter_id(jar: CookieJar) -> (CookieJar, Uuid) {
|
||||
|
|
@ -51,6 +60,37 @@ async fn upvote_handler(
|
|||
}
|
||||
}
|
||||
|
||||
async fn downvote_handler(
|
||||
jar: CookieJar,
|
||||
Path(slug): Path<String>,
|
||||
State(state): State<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
let (jar, voter_id) = get_or_init_voter_id(jar);
|
||||
|
||||
match delete_vote(&slug, &voter_id, &state.db).await {
|
||||
Ok(()) => (StatusCode::OK, jar, "Successfully upvoted"),
|
||||
Err(err) => {
|
||||
println!("{err}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, jar, "Failed to upvote")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_votes_and_voted_handler(
|
||||
jar: CookieJar,
|
||||
Path(slug): Path<String>,
|
||||
State(state): State<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
let (jar, voter_id) = get_or_init_voter_id(jar);
|
||||
match get_votes_and_voted(&slug, &voter_id, &state.db).await {
|
||||
Ok(votes_and_voted) => (StatusCode::OK, jar, Json(votes_and_voted)).into_response(),
|
||||
Err(err) => {
|
||||
println!("{err}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, jar, "Failed to upvote").into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use axum::{
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue