feat(api): added json body deserialization to the api endpoints

This commit is contained in:
antifallobst 2023-08-12 13:50:20 +02:00
parent 25934dff07
commit 49eb7cb524
Signed by: antifallobst
GPG Key ID: 2B4F402172791BAF
4 changed files with 53 additions and 7 deletions

15
Cargo.lock generated
View File

@ -284,6 +284,7 @@ version = "0.1.0"
dependencies = [
"actix-web",
"anyhow",
"serde",
"tokio",
]
@ -895,6 +896,20 @@ name = "serde"
version = "1.0.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32ac8da02677876d532745a130fc9d8e6edfa81a269b107c5b00829b91d8eb3c"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aafe972d60b0b9bee71a91b92fee2d4fb3c9d7e8f6b179aa99f27203d99a4816"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.28",
]
[[package]]
name = "serde_json"

View File

@ -10,3 +10,4 @@ license = "MIT"
tokio = { version = "1.29", features = ["macros", "rt-multi-thread", "sync"] }
anyhow = "1.0"
actix-web = "4"
serde = { version = "1.0.183", features = ["derive"] }

View File

@ -1,5 +1,6 @@
use actix_web::{post, web, App, HttpResponse, HttpServer, Responder};
use anyhow::Result;
use serde::Deserialize;
use tokio::sync::{mpsc, oneshot};
use crate::call::Call;
@ -8,11 +9,27 @@ struct ApiState {
tx: mpsc::Sender<(Call, oneshot::Sender<Result<()>>)>,
}
#[derive(Debug, Deserialize)]
struct AuthenticateData {
username: String,
password: String,
}
#[post("/authenticate")]
async fn authenticate(data: web::Data<ApiState>) -> impl Responder {
async fn authenticate(
data: web::Data<ApiState>,
body: web::Json<AuthenticateData>,
) -> impl Responder {
let (tx, rx) = oneshot::channel();
if let Err(_) = data.tx.send((Call::Authenticate, tx)).await {
if let Err(_) = data
.tx
.send((
Call::Authenticate(body.username.clone(), body.password.clone()),
tx,
))
.await
{
return HttpResponse::InternalServerError().finish();
}
@ -22,11 +39,24 @@ async fn authenticate(data: web::Data<ApiState>) -> impl Responder {
}
}
#[derive(Debug, Deserialize)]
struct RegisterData {
username: String,
password: String,
}
#[post("/register")]
async fn register(data: web::Data<ApiState>) -> impl Responder {
async fn register(data: web::Data<ApiState>, body: web::Json<RegisterData>) -> impl Responder {
let (tx, rx) = oneshot::channel();
if let Err(_) = data.tx.send((Call::Register, tx)).await {
if let Err(_) = data
.tx
.send((
Call::Register(body.username.clone(), body.password.clone()),
tx,
))
.await
{
return HttpResponse::InternalServerError().finish();
}

View File

@ -3,9 +3,9 @@ use tokio::sync::{mpsc, oneshot};
#[derive(Debug)]
pub enum Call {
Register,
Authenticate,
Delete,
Register(String, String),
Authenticate(String, String),
Delete(String),
}
async fn worker(mut rx: mpsc::Receiver<(Call, oneshot::Sender<Result<()>>)>) -> Result<()> {