50 lines
1.4 KiB
Rust
50 lines
1.4 KiB
Rust
use actix_web::{put, web, HttpRequest, HttpResponse, Responder, Result};
|
|
use bank::account::AccountError;
|
|
use serde::Serialize;
|
|
|
|
use crate::handlers::error::HttpAccountError;
|
|
use crate::handlers::AmountData;
|
|
use crate::AppState;
|
|
|
|
#[derive(Serialize)]
|
|
struct AccountCreated {
|
|
nr: String,
|
|
}
|
|
|
|
#[put("/{nr}")]
|
|
pub async fn route(
|
|
info: web::Path<String>,
|
|
form: web::Form<AmountData>,
|
|
data: web::Data<AppState>,
|
|
req: HttpRequest,
|
|
) -> Result<impl Responder> {
|
|
let nr = info.into_inner();
|
|
let amount = form.amount;
|
|
|
|
if amount <= 0_f64 {
|
|
return Err(HttpAccountError(AccountError::InvalidAmount).into());
|
|
}
|
|
|
|
info!("updating account {}...", nr);
|
|
|
|
let bank = data.bank.read().unwrap();
|
|
match bank.accounts.get(&nr) {
|
|
None => Err(HttpAccountError(AccountError::NotFound).into()),
|
|
Some(account) => {
|
|
let mut account = account.write().unwrap();
|
|
let hash = account.hash_string();
|
|
if let Some(etag) = req.headers().get("If-Match") {
|
|
let etag = etag.to_str().unwrap_or("");
|
|
if etag != hash {
|
|
Ok(HttpResponse::PreconditionFailed().finish())
|
|
} else {
|
|
account.balance = amount;
|
|
Ok(HttpResponse::Ok().finish())
|
|
}
|
|
} else {
|
|
Ok(HttpResponse::PreconditionRequired().finish())
|
|
}
|
|
}
|
|
}
|
|
}
|