Created
April 16, 2020 05:55
-
-
Save PurpleBooth/fd65f63396ea9dc484066b51e313c6ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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