#![allow(dead_code)]
use apify_client::ApifyClient;
const DEFAULT_API_URL: &str = "https://api.apify.com/v2";
pub fn make_client() -> Option<ApifyClient> {
let token = std::env::var("APIFY_TOKEN")
.ok()
.filter(|t| !t.is_empty())?;
let api_url = std::env::var("APIFY_API_URL")
.ok()
.filter(|u| !u.is_empty());
let base_url = resolve_base_url(api_url.as_deref());
Some(
ApifyClient::builder()
.token(token)
.base_url(base_url)
.build(),
)
}
pub fn resolve_base_url(api_url: Option<&str>) -> String {
let url = api_url.unwrap_or(DEFAULT_API_URL);
url.trim_end_matches('/')
.trim_end_matches("/v2")
.to_string()
}
#[macro_export]
macro_rules! require_client {
() => {{
match $crate::common::make_client() {
Some(client) => client,
None => {
eprintln!("Skipping: APIFY_TOKEN is not set");
return;
}
}
}};
}
pub struct Cleanup {
action: Option<Box<dyn FnOnce() + Send>>,
}
impl Cleanup {
pub fn new<F, Fut>(action: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: std::future::Future<Output = ()> + 'static,
{
let handle = tokio::runtime::Handle::current();
Cleanup {
action: Some(Box::new(move || {
handle.block_on(action());
})),
}
}
}
impl Drop for Cleanup {
fn drop(&mut self) {
if let Some(action) = self.action.take() {
let _ = std::thread::spawn(action).join();
}
}
}
pub fn unique_name(prefix: &str) -> String {
let uuid = uuid::Uuid::new_v4().simple().to_string();
format!("rust-test-{prefix}-{}", &uuid[..12])
}