Skip to content

Commit

Permalink
fix the response Body
Browse files Browse the repository at this point in the history
  • Loading branch information
rahul007-bit committed Feb 9, 2024
1 parent 3bf3c0a commit 0aa97b4
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 12 deletions.
3 changes: 2 additions & 1 deletion JS/wasm/crates/apis/src/http/shims/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
14 changes: 14 additions & 0 deletions JS/wasm/crates/serve/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ pub struct WasmInput<'a> {
params: HashMap<String, String>,
}

#[derive(Deserialize, Debug)]
pub struct WasmOutput {
pub headers: HashMap<String, String>,
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();
Expand Down Expand Up @@ -59,3 +68,8 @@ impl<'a> WasmInput<'a> {
parsed_headers
}
}
impl WasmOutput {
pub fn body(&self) -> String {
self.body.clone()
}
}
41 changes: 36 additions & 5 deletions JS/wasm/crates/serve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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 {
Expand Down Expand Up @@ -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::<WasmOutput>(&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);
Expand Down
6 changes: 3 additions & 3 deletions JS/wasm/crates/wasmjs-runtime/src/io.rs
Original file line number Diff line number Diff line change
@@ -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> {
Expand All @@ -15,7 +15,7 @@ pub struct WasmInput<'a> {
headers: HashMap<String, String>,
body: &'a str,
params: HashMap<String, String>,
geo: Map<String, SerdeValue>
geo: Map<String, SerdeValue>,
}

impl<'a> WasmInput<'a> {
Expand All @@ -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(),
}
}

Expand Down
13 changes: 10 additions & 3 deletions JS/wasm/examples/ec-wasmjs-hono/src/index.js
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -21,6 +20,14 @@ app.get("/vars", async (c) => {
}
});

app.get("/:username", (c) => {
const { username } = c.req.param();
return c.html(
html`<!doctype html>
<h1>Hello! ${username}!</h1>`,
);
});

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

0 comments on commit 0aa97b4

Please sign in to comment.