Skip to content

Commit

Permalink
refactor: Use macros convert req to js_value_map
Browse files Browse the repository at this point in the history
Signed-off-by: zu1k <i@zu1k.com>
  • Loading branch information
zu1k committed Mar 19, 2022
1 parent 27d41a5 commit daa1345
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 85 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ check:
clippy:
cargo clippy

prepare: fmt fix check clippy
prepare: fmt check clippy fix

CROSS_TARGET_LIST = \
x86_64-unknown-linux-musl \
Expand Down
2 changes: 0 additions & 2 deletions src/ca/root.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::error::Error;
use chrono::Utc;
use cookie::time::OffsetDateTime;
use http::uri::Authority;
use moka::future::Cache;
Expand Down Expand Up @@ -73,7 +72,6 @@ impl CertificateAuthority {
}

fn gen_cert(&self, authority: &Authority) -> rustls::Certificate {
let _now = Utc::now();
let mut params = rcgen::CertificateParams::default();

{
Expand Down
120 changes: 38 additions & 82 deletions src/rule/action/js.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use anyhow::{anyhow, Result};
use http::{header::HeaderName, Response};
use hyper::{body::*, Request};
use hyper::{
body::{to_bytes, Body, Bytes},
Request,
};
use quick_js::{console::LogConsole, Context, JsValue};
use std::collections::HashMap;

pub async fn modify_req(code: &str, req: Request<Body>) -> Result<Request<Body>> {
let (mut parts, body) = req.into_parts();
let mut body_bytes = Bytes::default();

let req_js = {
macro_rules! to_js_value_map {
($parts:ident, $body_bytes:ident) => {{
let mut req_js = HashMap::new();

// headers
let headers = {
let mut headers = HashMap::new();
for (name, value) in &parts.headers {
for (name, value) in &$parts.headers {
headers.insert(
name.to_string(),
JsValue::String(value.to_str().unwrap_or_default().to_owned()),
Expand All @@ -25,37 +25,30 @@ pub async fn modify_req(code: &str, req: Request<Body>) -> Result<Request<Body>>
req_js.insert("headers".to_owned(), JsValue::Object(headers));

// body text
match to_bytes(body).await {
Ok(content) => {
body_bytes = content.clone();
if let Ok(text) = String::from_utf8(content.to_vec()) {
req_js.insert("body".to_owned(), JsValue::String(text));
} else {
req_js.insert("body".to_owned(), JsValue::Undefined);
}
}
Err(_) => {
req_js.insert("body".to_owned(), JsValue::Undefined);
}
if let Ok(text) = String::from_utf8($body_bytes.to_vec()) {
req_js.insert("body".to_owned(), JsValue::String(text));
} else {
req_js.insert("body".to_owned(), JsValue::Undefined);
}
req_js.insert(
"method".to_owned(),
JsValue::String(parts.method.to_string()),
);
req_js.insert("url".to_owned(), JsValue::String(parts.uri.to_string()));

JsValue::Object(req_js)
};

let context = Context::builder().console(LogConsole).build()?;
req_js
}};
}

let data = {
let mut req = HashMap::new();
req.insert("request".to_owned(), req_js);
JsValue::Object(req)
};
context.set_global("data", data)?;
pub async fn modify_req(code: &str, req: Request<Body>) -> Result<Request<Body>> {
let (mut parts, body) = req.into_parts();
let body_bytes = to_bytes(body).await.unwrap_or_default();
let mut req_js = to_js_value_map!(parts, body_bytes);
req_js.insert(
"method".to_owned(),
JsValue::String(parts.method.to_string()),
);
req_js.insert("url".to_owned(), JsValue::String(parts.uri.to_string()));
let mut data = HashMap::new();
data.insert("request".to_owned(), JsValue::Object(req_js));

let context = Context::builder().console(LogConsole).build()?;
context.set_global("data", JsValue::Object(data))?;
match context.eval(code) {
Ok(req_js) => {
if let JsValue::Object(req_js) = req_js {
Expand All @@ -79,61 +72,24 @@ pub async fn modify_req(code: &str, req: Request<Body>) -> Result<Request<Body>>
} else {
body_bytes
};
return Ok(Request::from_parts(parts, Body::from(body)));
Ok(Request::from_parts(parts, Body::from(body)))
} else {
return Err(anyhow!("can not get js eval ret"));
};
Err(anyhow!("can not get js eval ret"))
}
}
Err(err) => Err(err.into()),
}
}

pub async fn modify_res(code: &str, res: Response<Body>) -> Result<Response<Body>> {
let (mut parts, body) = res.into_parts();
let mut body_bytes = Bytes::default();

let res_js = {
let mut res_js = HashMap::new();

// headers
let headers = {
let mut headers = HashMap::new();
for (name, value) in &parts.headers {
headers.insert(
name.to_string(),
JsValue::String(value.to_str().unwrap_or_default().to_owned()),
);
}
headers
};
res_js.insert("headers".to_owned(), JsValue::Object(headers));

// body text
match to_bytes(body).await {
Ok(content) => {
body_bytes = content.clone();
if let Ok(text) = String::from_utf8(content.to_vec()) {
res_js.insert("body".to_owned(), JsValue::String(text));
} else {
res_js.insert("body".to_owned(), JsValue::Undefined);
}
}
Err(_) => {
res_js.insert("body".to_owned(), JsValue::Undefined);
}
}

JsValue::Object(res_js)
};
let body_bytes = to_bytes(body).await.unwrap_or_default();
let res_js = to_js_value_map!(parts, body_bytes);
let mut data = HashMap::new();
data.insert("response".to_owned(), JsValue::Object(res_js));

let context = Context::builder().console(LogConsole).build()?;
let data = {
let mut req = HashMap::new();
req.insert("response".to_owned(), res_js);
JsValue::Object(req)
};
context.set_global("data", data)?;

context.set_global("data", JsValue::Object(data))?;
match context.eval(code) {
Ok(req_js) => {
if let JsValue::Object(req_js) = req_js {
Expand All @@ -153,10 +109,10 @@ pub async fn modify_res(code: &str, res: Response<Body>) -> Result<Response<Body
} else {
body_bytes
};
return Ok(Response::from_parts(parts, Body::from(body)));
Ok(Response::from_parts(parts, Body::from(body)))
} else {
return Err(anyhow!("can not get js eval ret"));
};
Err(anyhow!("can not get js eval ret"))
}
}
Err(err) => Err(err.into()),
}
Expand Down

1 comment on commit daa1345

@vercel
Copy link

@vercel vercel bot commented on daa1345 Mar 19, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.