Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chat with pdf ( Work in progress ) #326

Closed
wants to merge 6 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Implemented get method for Fetch from wasm
  • Loading branch information
redoC-A2k committed Apr 9, 2024
commit 48275d74a364b6ab4f2df871cae08e53bb426646
26 changes: 24 additions & 2 deletions JS/wasm/crates/apis/src/http/mod.rs
Original file line number Diff line number Diff line change
@@ -71,7 +71,29 @@ fn fetch_callback(
));
}
};

todo!("fetch");
let mut headers_map: HashMap<String, JSValue> = HashMap::new();
for (key, value) in response["headers"].as_object().unwrap() {
headers_map.insert(
key.to_string(),
JSValue::String(value.as_str().unwrap().to_string()),
);
}
let mut response_map: HashMap<String, JSValue> = HashMap::new();
response_map.insert(
"status".to_string(),
JSValue::Int(response["status"].as_i64().unwrap().try_into().unwrap()),
);
response_map.insert(
"statusText".to_string(),
JSValue::String(response["statusText"].as_str().unwrap().to_string()),
);
response_map.insert(
"body".to_string(),
JSValue::String(response["body"].as_str().unwrap().to_string()),
);
response_map.insert("headers".to_string(), JSValue::Object(headers_map));
let response_obj = JSValue::Object(response_map);
// todo!("fetch");
Ok(response_obj)
}
}
20 changes: 18 additions & 2 deletions JS/wasm/crates/serve/src/binding.rs
Original file line number Diff line number Diff line change
@@ -265,15 +265,31 @@ pub fn add_fetch_to_linker(linker: &mut Linker<WasiCtx>) -> anyhow::Result<()> {
},
)?;
// add the fetch_output_len and fetch_output functions here
let response_clone = response.clone();
linker.func_wrap("arakoo", "get_response_len", move || -> i32 {
todo!("get_response_len")
let response_clone = response_clone.clone();
let response = response_clone.lock().unwrap().clone();
response.len() as i32
})?;

// also add the fetch_error_len and fetch_error functions here
linker.func_wrap(
"arakoo",
"get_response",
move |mut _caller: Caller<'_, WasiCtx>, _ptr: i32| todo!("get_response"),
move |mut _caller: Caller<'_, WasiCtx>, ptr: i32| {
let response_clone = response.clone();
let mem = match _caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Trap::NullReference.into()),
};
let offset = ptr as u32 as usize;
let response = response_clone.lock().unwrap().clone();
match mem.write(&mut _caller, offset, response.as_bytes()) {
Ok(_) => {}
_ => return Err(Trap::MemoryOutOfBounds.into()),
};
Ok(())
},
)?;
Ok(())
}
20 changes: 20 additions & 0 deletions JS/wasm/examples/hono-fetch/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { build } from "esbuild";

let runtime = process.argv[2];

build({
entryPoints: ["src/index.js"],
bundle: true,
minify: false,
outfile: "bin/app.js",
format: "esm",
target: "esnext",
platform: "node",
// external: ["arakoo"],
define: {
"process.env.arakoo": JSON.stringify(runtime === "arakoo"),
},
}).catch((error) => {
console.error(error);
process.exit(1);
});
19 changes: 19 additions & 0 deletions JS/wasm/examples/hono-fetch/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "hono-fetch",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.6.8",
"esbuild": "^0.20.2",
"hono": "^3.9",
"javy": "^0.1.2"
},
"type": "module"
}
71 changes: 71 additions & 0 deletions JS/wasm/examples/hono-fetch/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Hono } from "hono";
import { readFileSync, writeFileSync, STDIO } from "javy/fs"
// import axios from "axios";
const app = new Hono();

function writeOutput(output) {
// const encodedOutput = new TextEncoder().encode(JSON.stringify(output));
const encodedOutput = new TextEncoder().encode(output);
const buffer = new Uint8Array(encodedOutput);
// Stdout file descriptor
writeFileSync(STDIO.Stdout, buffer);
}

app.get("/hello", (c) => {
return c.text("Hello World")
})

app.get('/post', async (c) => {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
console.log(response);
let body = JSON.parse(response.body);
response.body = body;
return c.json(response);
} catch (error) {
console.log("error occured")
writeOutput(error)
let output = JSON.stringify(error);
writeOutput(output)
return c.json(output);
}
})

app.get('/get', async (c) => {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1', { method: "GET" });
console.log(response);
let body = JSON.parse(response.body);
response.body = body;
return c.json(response);
} catch (error) {
console.log("error occured")
writeOutput(error)
let output = JSON.stringify(error);
writeOutput(output)
return c.json(output);
}
})

// app.get('/axiostest', async (c)=>{
// try {
// let response = await axos.get('https://jsonplaceholder.typicode.com/todos/1');
// console.log(response)
// console.log(response.data)
// } catch (error) {
// console.log("error occured")
// console.log(error)
// }
// })

app.fire()
Loading