Skip to main content

itchio_api/
purchases.rs

1use chrono::{DateTime, Utc};
2use serde::Deserialize;
3
4use crate::{Itchio, ItchioError, parsers::date_from_str};
5
6#[derive(Clone, Debug, Deserialize)]
7struct WrappedPurchases {
8  purchases: Vec<Purchase>
9}
10
11#[derive(Clone, Debug, Deserialize)] #[allow(dead_code)]
12pub struct Purchase {
13  id: u64,
14  #[serde(deserialize_with = "date_from_str")]
15  created_at: DateTime<Utc>,
16  game_id: u32,
17  sale_rate: u64,
18  /// Is true for any purchase that doesn’t have a download key associated with it, currently this only applies to web games
19  donation: bool,
20  price: String,
21  source: String,
22  email: String,
23}
24
25impl Itchio {
26  /// Gets the successful purchases from someone on a given game: <https://itch.io/docs/api/serverside#reference/gameviewpurchases-httpsitchioapi1keygamegame-idpurchases>
27  pub async fn get_purchases(&self, game_id: u32, lookup: &str, property_name: &str) -> Result<Vec<Purchase>, ItchioError> {
28    let url = format!("game/{}/purchases?{}={}", game_id, property_name, lookup);
29    let response = self.request::<WrappedPurchases>(url).await?;
30    Ok(response.purchases)
31  }
32}
33
34#[cfg(test)]
35mod tests {
36  use super::*;
37  // use std::env;
38  // use dotenv::dotenv;
39
40  // No one's ever purchased one of my games so I'm unable to test this, lol
41
42  // #[tokio::test]
43  // async fn good() {
44  //   dotenv().ok();
45  //   let client_secret = env::var("KEY").expect("KEY has to be set");
46  //   let api = Itchio::new(client_secret);
47  //   let purchases = api.get_purchases(
48  //     2295061,
49  //     "someone@somewhere.thatdoesnotexist",
50  //     "email"
51  //   ).await.inspect_err(|err| eprintln!("Error spotted: {}", err));
52  //   assert!(purchases.is_ok())
53  // }
54
55  #[tokio::test]
56  async fn bad_key() {
57    let api = Itchio::new("bad_key".to_string());
58    let purchases = api.get_purchases(
59      2295061,
60      "someone@somewhere.thatdoesnotexist",
61      "email"
62    ).await;
63    assert!(purchases.is_err_and(|err| matches!(err, ItchioError::BadKey)))
64  }
65}