Persist to KV

This commit is contained in:
SkyfallWasTaken 2024-07-01 18:53:28 +01:00
parent 50629e6a3b
commit 4084eb4568
3 changed files with 30 additions and 14 deletions

View file

@ -1,4 +1,4 @@
use indoc::{formatdoc, indoc}; use indoc::formatdoc;
use crate::items::ShopItem; use crate::items::ShopItem;

View file

@ -18,6 +18,8 @@ pub struct ShopItem {
#[serde(rename = "Stock")] #[serde(rename = "Stock")]
pub stock: Option<i32>, pub stock: Option<i32>,
pub id: String,
} }
pub type ShopItems = Vec<ShopItem>; pub type ShopItems = Vec<ShopItem>;

View file

@ -21,21 +21,35 @@ pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Respo
async fn run_scrape(env: Env) -> Result<String> { async fn run_scrape(env: Env) -> Result<String> {
let shop_url = Url::parse(&env.var("ARCADE_SHOP_URL")?.to_string())?; 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 available_items = items::try_fetch(shop_url).await?;
let mut result = Vec::new(); let Some(old_items) = kv.get("items").json::<items::ShopItems>().await? else {
for item in available_items { console_debug!("No old items found, storing new items");
result.push(format!( kv.put("items", &available_items)?.execute().await?;
"`{full_name}` - {price} {} - Stock: {stock}", return Ok("No old items found, storing new items".into());
if item.price == 1 { "ticket" } else { "tickets" }, };
full_name = item.full_name.trim(),
price = item.price, // Compare the old items with the new items.
stock = item let mut result: Vec<String> = Vec::new();
.stock for item in &available_items {
.map(|stock| stock.to_string()) // TODO: not very efficient.
.unwrap_or("Unlimited".into()) 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"))
} }