Implement the http variant of the bank server.
During that process, many shortcomings with the socket server and the bank lib were fixed. I am aware a massive commit like this is not ideal.
This commit is contained in:
parent
c69654a924
commit
dac95b7dae
34 changed files with 1797 additions and 140 deletions
44
http-server/src/handlers/transfer.rs
Normal file
44
http-server/src/handlers/transfer.rs
Normal file
|
@ -0,0 +1,44 @@
|
|||
use actix_web::{post, web, HttpResponse, Responder, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use bank::account::AccountError;
|
||||
|
||||
use crate::handlers::error::HttpAccountError;
|
||||
use crate::AppState;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct TransferData {
|
||||
pub(crate) from: String,
|
||||
pub(crate) to: String,
|
||||
pub(crate) amount: f64,
|
||||
}
|
||||
|
||||
#[post("/transfer")]
|
||||
pub async fn route(
|
||||
form: web::Form<TransferData>,
|
||||
data: web::Data<AppState>,
|
||||
) -> Result<impl Responder> {
|
||||
let from = form.from.clone();
|
||||
let to = form.to.clone();
|
||||
let amount = form.amount;
|
||||
|
||||
info!("transfering {} from {} to {}...", from, to, amount);
|
||||
|
||||
let bank = data.bank.read().unwrap();
|
||||
let from_acc = bank
|
||||
.accounts
|
||||
.get(&from)
|
||||
.ok_or(HttpAccountError(AccountError::NotFound))?;
|
||||
let mut from_acc = from_acc.write().unwrap();
|
||||
|
||||
let to_acc = bank
|
||||
.accounts
|
||||
.get(&to)
|
||||
.ok_or(HttpAccountError(AccountError::NotFound))?;
|
||||
let mut to_acc = to_acc.write().unwrap();
|
||||
|
||||
match bank.transfer(&mut from_acc, &mut to_acc, amount) {
|
||||
Err(e) => Err(HttpAccountError(e).into()),
|
||||
Ok(_) => Ok(HttpResponse::Ok().finish()),
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue