From 4084eb4568d452463b3b773906447f80030e0a97 Mon Sep 17 00:00:00 2001 From: SkyfallWasTaken Date: Mon, 1 Jul 2024 18:53:28 +0100 Subject: [PATCH] Persist to KV --- src/format.rs | 2 +- src/items.rs | 2 ++ src/lib.rs | 40 +++++++++++++++++++++++++++------------- 3 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/format.rs b/src/format.rs index 6577652..8b69dc0 100644 --- a/src/format.rs +++ b/src/format.rs @@ -1,4 +1,4 @@ -use indoc::{formatdoc, indoc}; +use indoc::formatdoc; use crate::items::ShopItem; diff --git a/src/items.rs b/src/items.rs index 8edddff..d834eb0 100644 --- a/src/items.rs +++ b/src/items.rs @@ -18,6 +18,8 @@ pub struct ShopItem { #[serde(rename = "Stock")] pub stock: Option, + + pub id: String, } pub type ShopItems = Vec; diff --git a/src/lib.rs b/src/lib.rs index 56bf737..c8cbe0a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,21 +21,35 @@ pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result Result { let shop_url = Url::parse(&env.var("ARCADE_SHOP_URL")?.to_string())?; + let kv = env.kv("SHOP_ITEMS")?; let available_items = items::try_fetch(shop_url).await?; - let mut result = Vec::new(); - for item in available_items { - result.push(format!( - "`{full_name}` - {price} {} - Stock: {stock}", - if item.price == 1 { "ticket" } else { "tickets" }, - full_name = item.full_name.trim(), - price = item.price, - stock = item - .stock - .map(|stock| stock.to_string()) - .unwrap_or("Unlimited".into()) - )); + let Some(old_items) = kv.get("items").json::().await? else { + console_debug!("No old items found, storing new items"); + kv.put("items", &available_items)?.execute().await?; + return Ok("No old items found, storing new items".into()); + }; + + // Compare the old items with the new items. + let mut result: Vec = Vec::new(); + for item in &available_items { + // TODO: not very efficient. + let old_item = old_items.iter().find(|i| i.id == item.id); + + match old_item { + Some(old) => { + if let Some(diff) = format::format_diff(old, item) { + result.push(diff); + } + } + None => { + result.push(format::format_new_item(item)); + } + } } - Ok(result.join("\n")) + // Now, let's persist the items to the KV store. + kv.put("items", &available_items)?.execute().await?; + + Ok(result.join("\n\n")) }