Skip to content

Commit

Permalink
feat: sending headers through request
Browse files Browse the repository at this point in the history
  • Loading branch information
wllfaria committed Jun 9, 2024
1 parent 63c12b8 commit e71b5a8
Show file tree
Hide file tree
Showing 9 changed files with 161 additions and 57 deletions.
2 changes: 1 addition & 1 deletion hac-client/src/pages/collection_viewer/request_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ mod auth_editor;
mod body_editor;
mod headers_editor;
mod headers_editor_delete_prompt;
mod headers_editor_form;
mod headers_editor_edit_form;

use auth_editor::AuthEditor;
use body_editor::{BodyEditor, BodyEditorEvent};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::ops::{Div, Sub};
use std::{cell::RefCell, ops::Add, rc::Rc};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hac_core::collection::header_map::HeaderMap;
use hac_core::collection::types::HeaderMap;
use rand::Rng;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Style, Stylize};
Expand All @@ -18,7 +18,7 @@ use ratatui::Frame;
use super::headers_editor_delete_prompt::{
HeadersEditorDeletePrompt, HeadersEditorDeletePromptEvent,
};
use super::headers_editor_form::{HeadersEditorForm, HeadersEditorFormEvent};
use super::headers_editor_edit_form::{HeadersEditorForm, HeadersEditorFormEvent};

#[derive(Debug)]
pub enum HeadersEditorEvent {
Expand Down Expand Up @@ -337,7 +337,17 @@ impl Eventful for HeadersEditor<'_> {

if let CollectionViewerOverlay::HeadersForm(_) = overlay {
match self.header_form.handle_key_event(key_event)? {
Some(HeadersEditorFormEvent::FinishEdit) => {}
Some(HeadersEditorFormEvent::Quit) => {
return Ok(Some(HeadersEditorEvent::Quit));
}
Some(HeadersEditorFormEvent::FinishEdit) => {
let mut store = self.collection_store.borrow_mut();
store.pop_overlay();
}
Some(HeadersEditorFormEvent::CancelEdit) => {
let mut store = self.collection_store.borrow_mut();
store.pop_overlay();
}
None => {}
}
return Ok(None);
Expand Down Expand Up @@ -420,6 +430,20 @@ impl Eventful for HeadersEditor<'_> {
.borrow_mut()
.push_overlay(CollectionViewerOverlay::HeadersForm(self.selected_row));
}
KeyCode::Char('n') => {
let idx = headers.len();
headers.push(HeaderMap {
pair: Default::default(),
enabled: true,
});

self.selected_row = idx;

drop(request);
self.collection_store
.borrow_mut()
.push_overlay(CollectionViewerOverlay::HeadersForm(idx));
}
_ => {}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use hac_core::collection::header_map::HeaderMap;

use crate::ascii::LOGO_ASCII;
use crate::pages::collection_viewer::collection_store::CollectionStore;
use crate::pages::collection_viewer::collection_viewer::CollectionViewerOverlay;
Expand All @@ -11,7 +9,7 @@ use std::cell::RefCell;
use std::ops::{Add, Div};
use std::rc::Rc;

use crossterm::event::{KeyCode, KeyEvent};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use rand::Rng;
use ratatui::layout::Rect;
use ratatui::style::Stylize;
Expand All @@ -22,6 +20,8 @@ use ratatui::Frame;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeadersEditorFormEvent {
FinishEdit,
CancelEdit,
Quit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand All @@ -46,6 +46,8 @@ pub struct HeadersEditorForm<'hef> {
header_idx: usize,
logo_idx: usize,
focused_input: HeadersEditorFormInput,
original_name: String,
original_value: String,
}

impl<'hef> HeadersEditorForm<'hef> {
Expand All @@ -61,14 +63,46 @@ impl<'hef> HeadersEditorForm<'hef> {
collection_store,
logo_idx,
focused_input: HeadersEditorFormInput::Name,
original_name: String::default(),
original_value: String::default(),
}
}

pub fn update(&mut self, header_idx: usize) -> anyhow::Result<()> {
self.header_idx = header_idx;

if !self.original_name.is_empty() || !self.original_value.is_empty() {
return Ok(());
}

let store = self.collection_store.borrow_mut();
let Some(request) = store.get_selected_request() else {
anyhow::bail!("trying to edit a header without a selected request");
};

let request = request.read().unwrap();
let Some(ref headers) = request.headers else {
anyhow::bail!("trying to edit a header that don't exist");
};

let CollectionViewerOverlay::HeadersForm(idx) = store.peek_overlay() else {
anyhow::bail!("tried to display the header form without the proper overlay set");
};

let header = headers
.get(idx)
.expect("selected a non-existing header to edit");

self.original_name = header.pair.0.to_string();
self.original_value = header.pair.1.to_string();

Ok(())
}

fn reset(&mut self) {
self.original_name.clear();
self.original_value.clear();
}
}

impl Renderable for HeadersEditorForm<'_> {
Expand Down Expand Up @@ -187,6 +221,10 @@ impl Eventful for HeadersEditorForm<'_> {
anyhow::bail!("selected header being edited doesnt exist on request");
};

if let (KeyCode::Char('c'), KeyModifiers::CONTROL) = (key_event.code, key_event.modifiers) {
return Ok(Some(HeadersEditorFormEvent::Quit));
}

match key_event.code {
KeyCode::Tab => self.focused_input = self.focused_input.next(),
KeyCode::BackTab => self.focused_input = self.focused_input.next(),
Expand All @@ -198,10 +236,20 @@ impl Eventful for HeadersEditorForm<'_> {
HeadersEditorFormInput::Name => header.pair.0.push(c),
HeadersEditorFormInput::Value => header.pair.1.push(c),
},
KeyCode::Esc => {}
KeyCode::Esc => {
header.pair = (self.original_name.clone(), self.original_value.clone());
drop(store);
self.reset();
return Ok(Some(HeadersEditorFormEvent::CancelEdit));
}
KeyCode::Enter => {
drop(store);
self.reset();
return Ok(Some(HeadersEditorFormEvent::FinishEdit));
}
_ => {}
};

Ok(Some(HeadersEditorFormEvent::FinishEdit))
Ok(None)
}
}
1 change: 0 additions & 1 deletion hac-core/src/collection.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#[allow(clippy::module_inception)]
pub mod collection;
pub mod header_map;
pub mod types;
pub use types::Collection;
mod errors;
34 changes: 0 additions & 34 deletions hac-core/src/collection/header_map.rs

This file was deleted.

8 changes: 6 additions & 2 deletions hac-core/src/collection/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use std::sync::{Arc, RwLock};

use serde::{Deserialize, Serialize};

use crate::collection::header_map::HeaderMap;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Collection {
pub info: Info,
Expand Down Expand Up @@ -43,6 +41,12 @@ impl RequestKind {
}
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct HeaderMap {
pub pair: (String, String),
pub enabled: bool,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RequestMethod {
Expand Down
1 change: 1 addition & 0 deletions hac-core/src/net.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod request_client;
pub mod request_manager;
pub mod request_strategies;
pub mod response_decoders;
Expand Down
61 changes: 61 additions & 0 deletions hac-core/src/net/request_client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use crate::collection::types::Request;

#[derive(Debug)]
pub struct RequestClient {
client: reqwest::Client,
}

impl RequestClient {
pub fn new() -> Self {
RequestClient {
client: reqwest::Client::new(),
}
}

pub fn get(&self, request: &Request) -> reqwest::RequestBuilder {
let request_builder = self.client.get(&request.uri);
self.append_headers(request, request_builder)
}

pub fn post(&self, request: &Request) -> reqwest::RequestBuilder {
let request_builder = self.client.post(&request.uri);
self.append_headers(request, request_builder)
}

pub fn put(&self, request: &Request) -> reqwest::RequestBuilder {
let request_builder = self.client.put(&request.uri);
self.append_headers(request, request_builder)
}

pub fn patch(&self, request: &Request) -> reqwest::RequestBuilder {
let request_builder = self.client.patch(&request.uri);
self.append_headers(request, request_builder)
}

pub fn delete(&self, request: &Request) -> reqwest::RequestBuilder {
let request_builder = self.client.delete(&request.uri);
self.append_headers(request, request_builder)
}

fn append_headers(
&self,
request: &Request,
mut request_builder: reqwest::RequestBuilder,
) -> reqwest::RequestBuilder {
if let Some(ref headers) = request.headers {
for header in headers.iter().filter(|header| header.enabled) {
let header_name = header.pair.0.clone();
let header_value = header.pair.1.clone();
request_builder = request_builder.header(header_name, header_value);
}
}

request_builder
}
}

impl Default for RequestClient {
fn default() -> Self {
Self::new()
}
}
23 changes: 12 additions & 11 deletions hac-core/src/net/request_strategies/http_strategy.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::collection::types::{Request, RequestMethod};
use crate::net::request_client::RequestClient;
use crate::net::request_manager::Response;
use crate::net::request_strategies::RequestStrategy;
use crate::net::response_decoders::{decoder_from_headers, ResponseDecoder};
Expand All @@ -7,7 +8,7 @@ pub struct HttpResponse;

impl RequestStrategy for HttpResponse {
async fn handle(&self, request: Request) -> Response {
let client = reqwest::Client::new();
let client = RequestClient::default();

match request.method {
RequestMethod::Get => self.handle_get_request(client, request).await,
Expand All @@ -20,9 +21,9 @@ impl RequestStrategy for HttpResponse {
}

impl HttpResponse {
async fn handle_get_request(&self, client: reqwest::Client, request: Request) -> Response {
async fn handle_get_request(&self, client: RequestClient, request: Request) -> Response {
let now = std::time::Instant::now();
match client.get(request.uri).send().await {
match client.get(&request).send().await {
Ok(response) => {
let decoder = decoder_from_headers(response.headers());
decoder.decode(response, now).await
Expand All @@ -42,10 +43,10 @@ impl HttpResponse {
}
}

async fn handle_post_request(&self, client: reqwest::Client, request: Request) -> Response {
async fn handle_post_request(&self, client: RequestClient, request: Request) -> Response {
let now = std::time::Instant::now();
match client
.post(request.uri)
.post(&request)
.json(&request.body.unwrap_or_default())
.send()
.await
Expand All @@ -69,10 +70,10 @@ impl HttpResponse {
}
}

async fn handle_put_request(&self, client: reqwest::Client, request: Request) -> Response {
async fn handle_put_request(&self, client: RequestClient, request: Request) -> Response {
let now = std::time::Instant::now();
match client
.put(request.uri)
.put(&request)
.json(&request.body.unwrap_or_default())
.send()
.await
Expand All @@ -96,10 +97,10 @@ impl HttpResponse {
}
}

async fn handle_patch_request(&self, client: reqwest::Client, request: Request) -> Response {
async fn handle_patch_request(&self, client: RequestClient, request: Request) -> Response {
let now = std::time::Instant::now();
match client
.patch(request.uri)
.patch(&request)
.json(&request.body.unwrap_or_default())
.send()
.await
Expand All @@ -123,10 +124,10 @@ impl HttpResponse {
}
}

async fn handle_delete_request(&self, client: reqwest::Client, request: Request) -> Response {
async fn handle_delete_request(&self, client: RequestClient, request: Request) -> Response {
let now = std::time::Instant::now();
match client
.delete(request.uri)
.delete(&request)
.json(&request.body.unwrap_or_default())
.send()
.await
Expand Down

0 comments on commit e71b5a8

Please sign in to comment.