|
| 1 | +use crate::{ |
| 2 | + errors::HttpClientError, |
| 3 | + response::{ReadiedResponse, RESPONSE_CLASS_NAME}, |
| 4 | +}; |
| 5 | + |
| 6 | +use phper::{classes::DynamicClass, functions::Argument, objects::Object}; |
| 7 | +use reqwest::blocking::{Client, ClientBuilder}; |
| 8 | +use std::time::Duration; |
| 9 | + |
| 10 | +const HTTP_CLIENT_CLASS_NAME: &'static str = "HttpClient\\HttpClient"; |
| 11 | + |
| 12 | +pub fn make_client_class() -> DynamicClass<Client> { |
| 13 | + let mut class = DynamicClass::new_with_constructor(HTTP_CLIENT_CLASS_NAME, || { |
| 14 | + let client = ClientBuilder::new() |
| 15 | + .timeout(Duration::from_secs(15)) |
| 16 | + .build()?; |
| 17 | + Ok::<_, HttpClientError>(client) |
| 18 | + }); |
| 19 | + |
| 20 | + class.add_method( |
| 21 | + "get", |
| 22 | + |this, arguments| { |
| 23 | + let url = arguments[0].as_string()?; |
| 24 | + let client = this.as_state(); |
| 25 | + let response = client.get(url).send()?; |
| 26 | + |
| 27 | + let readied_response = ReadiedResponse { |
| 28 | + status: response.status(), |
| 29 | + remote_addr: response.remote_addr(), |
| 30 | + headers: response.headers().clone(), |
| 31 | + body: response.bytes()?, |
| 32 | + }; |
| 33 | + |
| 34 | + let mut response_object = |
| 35 | + Object::<Option<ReadiedResponse>>::new_by_class_name(RESPONSE_CLASS_NAME)?; |
| 36 | + *response_object.as_mut_state() = Some(readied_response); |
| 37 | + |
| 38 | + Ok::<_, HttpClientError>(response_object) |
| 39 | + }, |
| 40 | + vec![Argument::by_val("url")], |
| 41 | + ); |
| 42 | + |
| 43 | + class |
| 44 | +} |
0 commit comments