From c89aa4a9f9b24c698c69228abed3f8b89293bf28 Mon Sep 17 00:00:00 2001 From: Cecylia Bocovich Date: Sun, 29 Jan 2023 14:18:39 -0500 Subject: [PATCH] Add function to start a resource-stream connection At the moment the start_stream function very simply prints out each response as it arrives. --- crates/rdsys-backend/Cargo.toml | 5 ++- crates/rdsys-backend/src/http.rs | 52 ++++++++++++++++++++++++++++++++ crates/rdsys-backend/src/lib.rs | 2 ++ 3 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 crates/rdsys-backend/src/http.rs diff --git a/crates/rdsys-backend/Cargo.toml b/crates/rdsys-backend/Cargo.toml index 14adce3..43e6861 100644 --- a/crates/rdsys-backend/Cargo.toml +++ b/crates/rdsys-backend/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "rdsys-backend" +name = "rdsys_backend" version = "0.1.0" edition = "2021" @@ -7,4 +7,7 @@ edition = "2021" [dependencies] serde_json = "1" +futures-util = { version = "0.3"} serde = { version = "1", features = ["derive"]} + +reqwest = { version = "0.11", features = ["stream"]} diff --git a/crates/rdsys-backend/src/http.rs b/crates/rdsys-backend/src/http.rs new file mode 100644 index 0000000..b03d742 --- /dev/null +++ b/crates/rdsys-backend/src/http.rs @@ -0,0 +1,52 @@ +use reqwest::Client; +use futures_util::StreamExt; +use std::io; + +#[derive(Debug)] +pub enum Error { + Reqwest (reqwest::Error), + Io (io::Error), + JSON (serde_json::Error), +} + +impl From for Error { + fn from(value: serde_json::Error) -> Self { + Self::JSON(value) + } +} + +impl From for Error { + fn from(value: reqwest::Error) -> Self { + Self::Reqwest(value) + } +} + +impl From for Error { + fn from(value: io::Error) -> Self { + Self::Io(value) + } +} + +pub async fn start_stream(api_endpoint: String, name: String, token: String, resource_types: Vec ) -> Result<(), Error> { + + let req = crate::ResourceRequest { + request_origin: name, + resource_types: resource_types, + }; + let json = serde_json::to_string(&req)?; + + let auth_value = format!("Bearer {}",token); + + let client = Client::new(); + let mut stream = client.get(api_endpoint) + .header("Authorization", &auth_value) + .body(json) + .send() + .await? + .bytes_stream(); + + while let Some(chunk) = stream.next().await { + println!("Chunk: {:?}", chunk?); + }; + Ok(()) +} diff --git a/crates/rdsys-backend/src/lib.rs b/crates/rdsys-backend/src/lib.rs index 1887bea..2192df7 100644 --- a/crates/rdsys-backend/src/lib.rs +++ b/crates/rdsys-backend/src/lib.rs @@ -2,6 +2,8 @@ use std::collections::HashMap; use serde::{Deserialize, Serialize}; +pub mod http; + #[derive(Serialize)] pub struct ResourceRequest { request_origin: String,