From 4bcc848bb178d9e4372ba13b750d620cabc2a9ac Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Sat, 16 Jan 2021 21:38:22 -0500 Subject: move poking services into app boot after systemd notify Signed-off-by: Christine Dodrill --- lib/cfcache/src/lib.rs | 64 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 lib/cfcache/src/lib.rs (limited to 'lib/cfcache/src/lib.rs') diff --git a/lib/cfcache/src/lib.rs b/lib/cfcache/src/lib.rs new file mode 100644 index 0000000..baf6775 --- /dev/null +++ b/lib/cfcache/src/lib.rs @@ -0,0 +1,64 @@ +use reqwest::header; +use tracing::instrument; + +pub type Result = std::result::Result; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("json error: {0}")] + Json(#[from] serde_json::Error), + + #[error("request error: {0}")] + Request(#[from] reqwest::Error), + + #[error("invalid header value: {0}")] + InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue), +} + +pub struct Client { + zone_id: String, + cli: reqwest::Client, +} + +static USER_AGENT: &str = concat!( + "xesite ", + env!("CARGO_PKG_NAME"), + "/", + env!("CARGO_PKG_VERSION") +); + +impl Client { + pub fn new(api_key: String, zone_id: String) -> Result { + let mut headers = header::HeaderMap::new(); + headers.insert( + header::AUTHORIZATION, + header::HeaderValue::from_str(&format!("Bearer {}", api_key))?, + ); + + let cli = reqwest::Client::builder() + .user_agent(USER_AGENT) + .default_headers(headers) + .build()?; + + Ok(Self { zone_id, cli }) + } + + #[instrument(skip(self), err)] + pub async fn purge(&self, urls: Vec) -> Result { + #[derive(serde::Serialize)] + struct Files { + files: Vec, + } + + self.cli + .post(&format!( + "https://api.cloudflare.com/client/v4/zones/{}/purge_cache", + self.zone_id + )) + .json(&Files { files: urls }) + .send() + .await? + .error_for_status()?; + Ok(()) + } +} -- cgit v1.2.3