diff --git a/basics/json-validation/Cargo.toml b/basics/json-validation/Cargo.toml index 4c2218a..1a2741d 100644 --- a/basics/json-validation/Cargo.toml +++ b/basics/json-validation/Cargo.toml @@ -4,10 +4,11 @@ version = "1.0.0" edition = "2021" [dependencies] -actix-web = { version = "3", features = ["openssl"] } -env_logger = "0.8" +actix-web = { version = "4.0.0-beta.21", features = ["openssl"] } +awc = "3.0.0-beta.19" +env_logger = "0.9" futures = "0.3.1" serde = { version = "1.0.43", features = ["derive"] } serde_json = "1.0.16" -validator = "0.10" -validator_derive = "0.10" +validator = "0.14" +validator_derive = "0.14" diff --git a/basics/json-validation/src/main.rs b/basics/json-validation/src/main.rs index f1b12c5..471d256 100644 --- a/basics/json-validation/src/main.rs +++ b/basics/json-validation/src/main.rs @@ -12,18 +12,16 @@ // - POSTing json body // 3. chaining futures into a single response used by an async endpoint -use serde::{Deserialize, Serialize}; - -use std::collections::HashMap; -use std::io; - use actix_web::{ - client::Client, error::ErrorBadRequest, + http::StatusCode, web::{self, BytesMut}, App, Error, HttpResponse, HttpServer, }; +use awc::Client; use futures::StreamExt; +use serde::{Deserialize, Serialize}; +use std::io; use validator::Validate; use validator_derive::Validate; @@ -38,18 +36,14 @@ struct SomeData { #[allow(dead_code)] // it is debug printed #[derive(Debug, Deserialize)] struct HttpBinResponse { - args: HashMap, - data: String, - files: HashMap, - form: HashMap, - headers: HashMap, json: SomeData, - origin: String, - url: String, } /// validate data, post json to httpbin, get it back in the response body, return deserialized -async fn step_x(data: SomeData, client: &Client) -> Result { +async fn step_x( + data: SomeData, + client: &Client, +) -> Result { // validate data data.validate().map_err(ErrorBadRequest)?; @@ -57,7 +51,8 @@ async fn step_x(data: SomeData, client: &Client) -> Result { .post("https://httpbin.org/post") .send_json(&data) .await - .map_err(Error::from)?; // <- convert SendRequestError to an Error + // <- convert SendRequestError to an InternalError, a type that implements the ResponseError trait + .map_err(actix_web::error::ErrorInternalServerError)?; // <- convert it into an actix_web::Error let mut body = BytesMut::new(); while let Some(chunk) = res.next().await { @@ -93,7 +88,7 @@ async fn main() -> io::Result<()> { println!("Starting server at: {:?}", endpoint); HttpServer::new(|| { App::new() - .data(Client::default()) + .app_data(web::Data::new(Client::default())) .service(web::resource("/something").route(web::post().to(create_something))) }) .bind(endpoint)?