Engage endpoint

This commit is contained in:
Imbus 2024-03-22 21:28:20 +01:00
parent 6fcbb92691
commit d93dc7fd89
4 changed files with 73 additions and 0 deletions

View file

@ -126,3 +126,18 @@ export async function submitLogin(
if (response.ok) return await response.json();
}
/**
* Engage with a post.
* @param postId The id of the post to engage with.
* @param token The token of the user engaging with the post.
* @returns {Promise<Response>} A promise that resolves to a Response object.
*/
export async function engage(postId: string, token: string): Promise<Response> {
return await fetch(`/api/posts/${postId}/engage`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO engagements (post_id, user_id) VALUES ($1, (SELECT id FROM users WHERE username = $2))",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "2374223a11247bf75811f4cc846e9ab89e1a31a78a5be0c6d38d91e3a197af41"
}

View file

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS engagements (
user_id BIGINT NOT NULL,
post_id BIGINT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (post_id) REFERENCES posts (id),
PRIMARY KEY (user_id, post_id)
);

View file

@ -4,6 +4,7 @@ use crate::types::{NewPost, PostQueryParams};
use crate::ServerState;
use actix_web::web::{Data, Path, Query};
use actix_web::HttpRequest;
use actix_web::{get, post, web::Json, HttpResponse, Responder, Result};
use log::info;
@ -59,6 +60,41 @@ pub async fn new_post(
};
}
#[post("/posts/{id}/engage")]
pub async fn engage_post(
path: Path<i64>,
state: Data<ServerState>,
auth: Data<Authentication>,
req: HttpRequest,
) -> Result<impl Responder> {
// Token from header
let token = req
.headers()
.get("Authorization")
.unwrap()
.to_str()
.unwrap();
let claims = auth.decode(token);
if let Err(e) = claims {
info!("Error validating token: {}", e);
return Ok(HttpResponse::BadRequest().json("Error"));
}
let post_id = path.into_inner();
let username = claims.unwrap().sub;
let q = sqlx::query!(
"INSERT INTO engagements (post_id, user_id) VALUES ($1, (SELECT id FROM users WHERE username = $2))",
post_id,
username
);
q.execute(&state.pool).await.unwrap();
return Ok(HttpResponse::Ok().json("Engaged"));
}
#[get("posts/{id}")]
pub async fn post_by_id(path: Path<i64>, state: Data<ServerState>) -> Result<impl Responder> {
let id = path.into_inner();