use std::collections::HashMap;
use anyhow::{Context, Result};
use axum::body::Body;
use bytes::Bytes;
pub async fn encode_request(
req: axum::http::Request<Body>,
max_body_size: usize,
) -> Result<serde_json::Value> {
let (parts, body) = req.into_parts();
let body_bytes = axum::body::to_bytes(body, max_body_size)
.await
.context("read request body")?;
let headers: HashMap<String, String> = parts
.headers
.iter()
.filter_map(|(k, v)| Some((k.to_string(), v.to_str().ok()?.to_string())))
.collect();
Ok(serde_json::json!({
"method": parts.method.to_string(),
"uri": parts.uri.to_string(),
"headers": headers,
"body": String::from_utf8_lossy(&body_bytes),
}))
}
pub fn decode_response(value: serde_json::Value) -> Result<axum::http::Response<Body>> {
let status = value.get("status").and_then(|v| v.as_u64()).unwrap_or(200) as u16;
let body = value.get("body").and_then(|v| v.as_str()).unwrap_or("");
let mut builder = axum::http::Response::builder().status(status);
if let Some(headers) = value.get("headers").and_then(|v| v.as_object()) {
for (k, v) in headers {
if let Some(v_str) = v.as_str() {
builder = builder.header(k.as_str(), v_str);
}
}
}
builder
.body(Body::from(Bytes::from(body.to_string())))
.context("build response")
}