mirror of
https://github.com/SkyfallWasTaken/arcade-monitor.git
synced 2024-11-10 03:49:40 +00:00
Persist to KV
This commit is contained in:
parent
50629e6a3b
commit
4084eb4568
3 changed files with 30 additions and 14 deletions
|
@ -1,4 +1,4 @@
|
|||
use indoc::{formatdoc, indoc};
|
||||
use indoc::formatdoc;
|
||||
|
||||
use crate::items::ShopItem;
|
||||
|
||||
|
|
|
@ -18,6 +18,8 @@ pub struct ShopItem {
|
|||
|
||||
#[serde(rename = "Stock")]
|
||||
pub stock: Option<i32>,
|
||||
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
pub type ShopItems = Vec<ShopItem>;
|
||||
|
|
40
src/lib.rs
40
src/lib.rs
|
@ -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> {
|
||||
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::<items::ShopItems>().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<String> = 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"))
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue