add conditional put

This commit is contained in:
Sebastian Hugentobler 2022-03-30 09:36:59 +02:00
parent b4fcbdfef8
commit 547b7b375a
Signed by: shu
GPG key ID: BB32CF3CA052C2F0
7 changed files with 87 additions and 21 deletions

View file

@ -27,8 +27,14 @@ pub async fn fetch_account(host: &str, nr: &str) -> Result<JsonAccount, FetchErr
}
}
pub async fn set_balance(host: &str, nr: &str, balance: f64) -> Result<(), FetchError> {
pub async fn set_balance(
host: &str,
nr: &str,
balance: f64,
etag: String,
) -> Result<(), FetchError> {
let data = JsValue::from_str(&format!("amount={}", balance));
client::put(&format! {"{}/accounts/{}", host, nr}, data).await?;
client::put(&format! {"{}/accounts/{}", host, nr}, data, Some(etag)).await?;
Ok(())
}

View file

@ -53,7 +53,7 @@ pub async fn get_json(url: &str) -> Result<Option<String>, FetchError> {
Ok(text.as_string())
}
pub async fn put(url: &str, data: JsValue) -> Result<(), FetchError> {
pub async fn put(url: &str, data: JsValue, if_match: Option<String>) -> Result<(), FetchError> {
let mut opts = RequestInit::new();
opts.method("PUT");
opts.mode(RequestMode::Cors);
@ -63,6 +63,11 @@ pub async fn put(url: &str, data: JsValue) -> Result<(), FetchError> {
request
.headers()
.set("Content-Type", "application/x-www-form-urlencoded")?;
if let Some(etag) = if_match {
request.headers().set("If-match", &etag)?;
}
self::send_request(request).await?;
Ok(())

View file

@ -77,8 +77,17 @@ impl Component for Main {
true
}
Event::SetBalance(balance, nr) => {
let acc = bank::account::Account {
number: nr.clone(),
owner: self.selected_owner.clone(),
balance: self.selected_balance,
is_active: true,
};
let hash = acc.hash_string();
ctx.link().send_future(async move {
match api::set_balance("http://localhost:8000", &nr, balance).await {
match api::set_balance("http://localhost:8000", &nr, balance, hash).await {
Err(e) => Event::ShowError(e.to_string()),
Ok(_) => Event::SelectAccountNr(nr),
}