use async_graphql_dataloader::{DataLoader, BatchLoad};
use std::collections::HashMap;
#[derive(Clone, Debug)]
struct User {
id: i32,
name: String,
}
struct UserLoader;
#[async_trait::async_trait]
impl BatchLoad for UserLoader {
type Key = i32;
type Value = User;
type Error = String;
async fn load(&self, keys: &[i32]) -> HashMap<i32, Result<User, String>> {
println!("π BATCH LOADING {} users: {:?}", keys.len(), keys);
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
keys.iter()
.map(|&id| {
let user = User {
id,
name: format!("User {}", id),
};
(id, Ok(user))
})
.collect()
}
}
#[tokio::main]
async fn main() {
println!("π Starting BASIC DataLoader example...");
let user_loader = DataLoader::new(UserLoader);
println!("π¦ Testing batch loading...");
let futures = vec![
user_loader.load(1),
user_loader.load(2),
user_loader.load(3),
];
let results = futures::future::join_all(futures).await;
for result in results {
match result {
Ok(user) => println!("β
User: {} - {}", user.id, user.name),
Err(e) => println!("β Error: {}", e),
}
}
println!("πΎ Testing cache...");
let cached_result = user_loader.load(1).await;
match cached_result {
Ok(user) => println!("β
Cached User 1: {}", user.name),
Err(e) => println!("β Cached Error: {}", e),
}
println!("ποΈ Testing cache clear...");
user_loader.clear();
let after_clear = user_loader.load(1).await;
match after_clear {
Ok(user) => println!("β
After clear User 1: {}", user.name),
Err(e) => println!("β After clear Error: {}", e),
}
println!("π BASIC example completed successfully!");
}