From 0aa97b44c299e8bbad0edce484705f662d4cb60b Mon Sep 17 00:00:00 2001 From: rahul007-bit Date: Fri, 9 Feb 2024 08:53:23 +0530 Subject: [PATCH] fix the response Body --- JS/wasm/crates/apis/src/http/shims/index.js | 3 +- JS/wasm/crates/serve/src/io.rs | 14 +++++++ JS/wasm/crates/serve/src/lib.rs | 41 +++++++++++++++++--- JS/wasm/crates/wasmjs-runtime/src/io.rs | 6 +-- JS/wasm/examples/ec-wasmjs-hono/src/index.js | 13 +++++-- 5 files changed, 65 insertions(+), 12 deletions(-) diff --git a/JS/wasm/crates/apis/src/http/shims/index.js b/JS/wasm/crates/apis/src/http/shims/index.js index c0e54bd58..1e271418f 100644 --- a/JS/wasm/crates/apis/src/http/shims/index.js +++ b/JS/wasm/crates/apis/src/http/shims/index.js @@ -283,9 +283,10 @@ const requestToHandler = (input) => { Promise.resolve(event.response) .then((res) => { result = { - data: res.body, + body: res.body, headers: res.headers.headers, status: res.status, + statusText: res.statusText, }; }) .catch((err) => { diff --git a/JS/wasm/crates/serve/src/io.rs b/JS/wasm/crates/serve/src/io.rs index ee0ea26ba..1a983625b 100644 --- a/JS/wasm/crates/serve/src/io.rs +++ b/JS/wasm/crates/serve/src/io.rs @@ -12,6 +12,15 @@ pub struct WasmInput<'a> { params: HashMap, } +#[derive(Deserialize, Debug)] +pub struct WasmOutput { + pub headers: HashMap, + pub status: u16, + #[serde(rename = "statusText")] + pub status_text: String, + body: String, +} + impl<'a> WasmInput<'a> { pub fn new(request: &'a Parts, body: &'a str) -> Self { let mut params = HashMap::new(); @@ -59,3 +68,8 @@ impl<'a> WasmInput<'a> { parsed_headers } } +impl WasmOutput { + pub fn body(&self) -> String { + self.body.clone() + } +} diff --git a/JS/wasm/crates/serve/src/lib.rs b/JS/wasm/crates/serve/src/lib.rs index 1b108342c..e759a86db 100644 --- a/JS/wasm/crates/serve/src/lib.rs +++ b/JS/wasm/crates/serve/src/lib.rs @@ -11,7 +11,11 @@ use std::{ use futures::future::{self, Ready}; use hyper::{ - http::request::Parts, server::conn::AddrStream, service::Service, Body, Request, Response, + header::{HeaderName, HeaderValue}, + http::request::Parts, + server::conn::AddrStream, + service::Service, + Body, Request, Response, }; use tracing::{error, event, info, Level}; @@ -21,7 +25,7 @@ use wasmtime_wasi::WasiCtxBuilder; use wasmtime::{Config, Engine, Instance, Linker, Memory, Module, Store}; -use crate::io::WasmInput; +use crate::io::{WasmInput, WasmOutput}; #[derive(Clone)] pub struct RequestService { @@ -76,11 +80,38 @@ impl WorkerCtx { let body = hyper::body::to_bytes(body).await.unwrap(); let body_str = String::from_utf8_lossy(&body).to_string(); let result = self.run(&parts, &body_str).await; - match result { Ok(output) => { - let response = Response::new(Body::from(output)); - Ok((response, None)) + let parsed_output = serde_json::from_slice::(&output); + match parsed_output { + Ok(parsed_output) => { + let mut response = Response::builder(); + response = response + .status(parsed_output.status); + + let headers = parsed_output.headers.clone(); + let headers_vec: Vec<(String, String)> = headers + .into_iter() + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + headers_vec.iter().for_each(|(key, value)| { + response.headers_mut().unwrap().insert( + HeaderName::from_bytes(key.as_bytes()).unwrap(), + HeaderValue::from_str(value).unwrap(), + ); + }); + let response = Response::new(Body::from(parsed_output.body())); + Ok((response, None)) + } + Err(e) => { + error!("Error: {}", e); + let response = Response::builder() + .status(500) + .body(Body::from("Internal Server Error")) + .unwrap(); + Ok((response, Some(e.into()))) + } + } } Err(e) => { error!("Error: {}", e); diff --git a/JS/wasm/crates/wasmjs-runtime/src/io.rs b/JS/wasm/crates/wasmjs-runtime/src/io.rs index c08511e3d..8d893516f 100644 --- a/JS/wasm/crates/wasmjs-runtime/src/io.rs +++ b/JS/wasm/crates/wasmjs-runtime/src/io.rs @@ -1,12 +1,12 @@ use std::{collections::HashMap, fmt::Debug}; +use crate::geolocation::GeolocationData; use actix_web::{ http::{header::HeaderMap, StatusCode, Uri}, HttpRequest, }; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value as SerdeValue}; -use crate::geolocation::GeolocationData; #[derive(Serialize, Deserialize, Debug)] pub struct WasmInput<'a> { @@ -15,7 +15,7 @@ pub struct WasmInput<'a> { headers: HashMap, body: &'a str, params: HashMap, - geo: Map + geo: Map, } impl<'a> WasmInput<'a> { @@ -34,7 +34,7 @@ impl<'a> WasmInput<'a> { headers: Self::build_headers_hash(request.headers()), body, params, - geo: geo_details.data.clone() + geo: geo_details.data.clone(), } } diff --git a/JS/wasm/examples/ec-wasmjs-hono/src/index.js b/JS/wasm/examples/ec-wasmjs-hono/src/index.js index 716c17c9a..2a36bc5e9 100644 --- a/JS/wasm/examples/ec-wasmjs-hono/src/index.js +++ b/JS/wasm/examples/ec-wasmjs-hono/src/index.js @@ -1,13 +1,12 @@ import { Hono } from "hono"; import { connect } from "@planetscale/database"; - +import { html } from "hono/html"; const app = new Hono(); const env = {}; app.get("/", (c) => { - return c.text("Hello World!"); + return c.text("Hello World!"); }); - app.get("/vars", async (c) => { try { const extVars = JSON.stringify({ @@ -21,6 +20,14 @@ app.get("/vars", async (c) => { } }); +app.get("/:username", (c) => { + const { username } = c.req.param(); + return c.html( + html` +

Hello! ${username}!

`, + ); +}); + app.get("/hello/:name", async (c) => { const name = c.req.param("name"); return c.text(`Async Hello ${name}!`);