Skip to content

Instantly share code, notes, and snippets.

@PurpleBooth
Created Apr 16, 2020
Embed
What would you like to do?
use std::collections::HashMap;
use futures::{stream, StreamExt};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::error::Error;
#[derive(Serialize, Deserialize, Debug)]
struct ProjectsItem {
hash_id: String,
}
type ProjectsData = Vec<ProjectsItem>;
#[derive(Serialize, Deserialize, Debug)]
struct ProjectsResponse {
data: ProjectsData
}
#[derive(Serialize, Deserialize, Debug)]
struct ProjectAsset {
image_url: String,
}
type ProjectAssets = Vec<ProjectsItem>;
#[derive(Serialize, Deserialize, Debug)]
struct ProjectResponse {
assets: ProjectAssets
}
const PARALLEL_REQUESTS: usize = 2;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let username = "anniehexample";
let projects_url = format!("https://example.com/users/{}/projects.json", username);
let client = Client::new();
let projects = client.get(&projects_url)
.send()
.await?
.json::<ProjectsResponse>()
.await?;
let mut stream = futures::stream::FuturesUnordered::new();
let bodies = stream::iter(projects.data)
.map(|project| {
let client = &client;
async move {
client.get(&format!("https://example.com/projects/{}.json", project.hash_id))
.send()
.await?
.json::<ProjectsResponse>()
.await
}
})
.buffer_unordered(PARALLEL_REQUESTS)
.await;
println!("{:#?}", bodies);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment