1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use crate::model::Zones;
use isahc::{prelude::Request, RequestExt, ResponseExt};

pub mod model;

pub async fn get_domain_id(
    domain: &str,
    cf_api: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let resp: Zones = Request::get("https://api.cloudflare.com/client/v4/zones")
        .header("Authorization", format!("Bearer {}", cf_api))
        .body(())?
        .send()?
        .json()?;

    for x in resp.result.iter() {
        if x.name == domain {
            return Ok(x.id.clone());
        }
    }
    Err("error: domain not found in zones".into())
}

pub async fn purge_file(
    zone: &str,
    url: &str,
    key: &str,
) -> Result<isahc::http::StatusCode, Box<dyn std::error::Error>> {
    Ok(Request::post(format!(
        "https://api.cloudflare.com/client/v4/zones/{}/purge_cache",
        zone
    ))
    .header("Authorization", format!("Bearer {}", key))
    .header("content-type", "application/json")
    .body(serde_json::to_vec(&model::PurgeFiles { files: vec![url] })?)?
    .send_async()
    .await?
    .status())
}