mirror of
https://github.com/SkyfallWasTaken/arcade-monitor.git
synced 2024-11-25 18:33:48 +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;
|
use crate::items::ShopItem;
|
||||||
|
|
||||||
|
|
|
@ -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>;
|
||||||
|
|
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> {
|
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"))
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue