Skip to content

Commit

Permalink
ReImplemented get method of axios
Browse files Browse the repository at this point in the history
  • Loading branch information
redoC-A2k committed Jun 11, 2024
1 parent da61ff9 commit f6f7de8
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 28 deletions.
57 changes: 57 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/axios/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use std::thread;
use std::time::Duration;

use anyhow::{anyhow, Result};
use log::debug;
// use crate::{types::{HttpRequest, HttpResponse}, JSApiSet};
use super::{
APIConfig, JSApiSet,
};
use javy::quickjs::{JSContextRef, JSValue, JSValueRef};
use quickjs_wasm_rs::{from_qjs_value, to_qjs_value};

pub(super) struct Axios;

impl JSApiSet for Axios {
fn register(&self, runtime: &javy::Runtime, _config: &APIConfig) -> Result<()> {
let context = runtime.context();
let global = context.global_object()?;
global
.set_property(
"setTimeout",
context
.wrap_callback(set_timeout_api())
.expect("unable to get result"),
)
.expect("unable to set property");

Ok(())
}
}

fn set_timeout_api() -> impl FnMut(&JSContextRef, JSValueRef, &[JSValueRef]) -> Result<JSValue> {
move |context: &JSContextRef, _this: JSValueRef, args: &[JSValueRef]| {
let callback = args.get(0).unwrap();
let default = to_qjs_value(context, &JSValue::Int(0)).unwrap();
let timeout = args.get(1).unwrap_or(&default);
thread::sleep(Duration::from_millis(
timeout
.as_f64()
.expect("Unable to convert timeout to milliseconds") as u64,
));
debug!("timeout reached");
if callback.is_function() {
let mut argsvec: Vec<JSValueRef> = vec![];
if args.len() > 2 {
for i in 2..args.len() {
argsvec.push(args.get(i).unwrap().to_owned())
}
}
let res = callback.call(
&to_qjs_value(context.to_owned(), &JSValue::Undefined).unwrap(),
&argsvec,
);
}
Ok(JSValue::Undefined)
}
}
60 changes: 38 additions & 22 deletions JS/wasm/crates/arakoo-core/src/apis/http/shims/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,14 +164,19 @@ class Headers {
}

class Request {
constructor(input) {
// console.log("In constructor of request input body len",input.body.byteLength);
this.url = input.uri;
constructor(url, input) {
console.debug("Request constructor called with ", JSON.stringify(url), input)
if (typeof url === "string") {
this.url = url
} else {
throw new Error("url in Request constructor is not a string")
}
this.headers = input.headers;
this.method = input.method;
this.headers = new Headers(input.headers || {});
let bodyArray = new Uint8Array(input.body);
let bodyString = decoder.decode(bodyArray);
if (bodyString != undefined && bodyString.length > 0) this.body = JSON.parse(bodyString);
if (bodyString != undefined && bodyString.length > 0)
this.body = JSON.parse(bodyString);
this.params = input.params || {};
this.geo = input.geo || {};
}
Expand Down Expand Up @@ -274,8 +279,8 @@ globalThis.addEventListener = (_eventName, handler) => {
handlerFunction = handler;
};

const requestToHandler = (input) => {
const request = new Request(input);
const requestToHandler = (inputReq) => {
const request = new Request(inputReq.uri,inputReq);
console.debug("Request recieved ", JSON.stringify(request));
const event = {
request,
Expand Down Expand Up @@ -340,39 +345,50 @@ function encodeBody(body) {
// return event;
// }


function fetch(uri, options) {
console.debug("In fetch function", uri, options);
let encodedBodyData =
options && options.body ? encodeBody(options.body) : new Uint8Array().buffer;
console.info("constructor name of uri ", uri.constructor.name);
console.info("uri is ", JSON.stringify(uri))
if (uri.constructor.name == "Request") {
console.info("uri is instance of Request")
options = {}
options.headers = uri.headers;
options.method = uri.method;
options.params = uri.params;
options.geo = uri.geo;
uri = uri.url;
}
console.info("In fetch function", uri, options)
let encodedBodyData = (options && options.body) ? encodeBody(options.body) : new Uint8Array().buffer
const { status, headers, body } = __internal_http_send({
method: (options && options.method) || "GET",
uri: uri instanceof URL ? uri.toString() : uri,
uri: (uri instanceof URL) ? uri.toString() : uri,
headers: (options && options.headers) || {},
body: encodedBodyData,
params: (options && options.params) || {},
});
console.debug("Response from fetch", status, headers, body);
})
console.info("Response from fetch", status, headers, body)
let obj;
try {
obj = {
status,
headers: {
entries: () => Object.entries(headers || {}),
get: (key) => (headers && headers[key]) || null,
has: (key) => (headers && headers[key] ? true : false),
has: (key) => (headers && headers[key]) ? true : false
},
arrayBuffer: () => Promise.resolve(body),
ok: status > 199 && status < 300,
ok: (status > 199 && status < 300),
statusText: httpStatus[status],
text: () => Promise.resolve(new TextDecoder().decode(body || new Uint8Array())),
json: () => {
let text = new TextDecoder().decode(body || new Uint8Array());
return Promise.resolve(JSON.parse(text));
},
};
let text = new TextDecoder().decode(body || new Uint8Array())
return Promise.resolve(JSON.parse(text))
}
}
} catch (error) {
console.log("Error occured in sending response from fetch");
console.log(error);
console.log("Error occured in sending response from fetch")
console.log(error)
}
return Promise.resolve(obj);
}
}
11 changes: 7 additions & 4 deletions JS/wasm/crates/arakoo-core/src/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@
//! invoked for the first time.
//! * `stream_io` - Registers implementations of `Javy.IO.readSync` and `Javy.IO.writeSync`.
use super::wit;
use anyhow::Result;
use javy::Runtime;
use super::wit;

pub use api_config::APIConfig;
pub use console::LogStream;
Expand All @@ -56,14 +56,16 @@ pub mod http;
pub mod types;

mod api_config;
mod axios;
mod console;
mod fetch;
mod jsonnet;
mod pdfparse;
mod random;
mod runtime_ext;
mod stream_io;
mod text_encoding;
mod pdfparse;
mod fetch;
mod jsonnet;

pub(crate) trait JSApiSet {
fn register(&self, runtime: &Runtime, config: &APIConfig) -> Result<()>;
}
Expand All @@ -88,5 +90,6 @@ pub fn add_to_runtime(runtime: &Runtime, config: APIConfig) -> Result<()> {
jsonnet::Jsonnet.register(runtime, &config)?;
pdfparse::PDFPARSER.register(runtime, &config)?;
fetch::Fetch.register(runtime, &config)?;
axios::Axios.register(runtime, &config)?;
Ok(())
}
2 changes: 1 addition & 1 deletion JS/wasm/crates/arakoo-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ impl wit::inbound_http::Guest for Guest {
let entrypoint = **HANDLER.get().unwrap();
entrypoint
.call(global, &[request_value])
.expect("Unable to call requestToEvent");
.expect("Unable to call handler");
// let event_request = event
// .get_property("request")
// .expect("Unable to get request from event");
Expand Down
3 changes: 2 additions & 1 deletion JS/wasm/crates/serve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ use wasmtime_wasi::{bindings, ResourceTable, WasiCtx, WasiCtxBuilder, WasiView};
use wasmtime::component::{Component, Linker};
use wasmtime::{Config, Engine, Store, WasmBacktraceDetails};
use wit::arakoo::edgechains::http_types;
use wit::exports::arakoo::edgechains::inbound_http::{self};
use wit::arakoo::edgechains::utils;
use wit::exports::arakoo::edgechains::inbound_http::{self};

use crate::{
// binding::add_jsonnet_to_linker,
Expand Down Expand Up @@ -189,6 +189,7 @@ impl WorkerCtx {
bindings::io::error::add_to_linker(&mut linker, |x| x).expect("Unable to add io error");
// bindings::sync::io::streams::add_to_linker(&mut linker, |x| x)
// .expect("Unable to add io streams");
bindings::io::poll::add_to_linker(&mut linker, |x| x).expect("unable to add io poll");
bindings::io::streams::add_to_linker(&mut linker, |x| x).expect("Unable to add io streams");
bindings::cli::stdin::add_to_linker(&mut linker, |x| x).expect("Unable to add cli stdin");
bindings::cli::stdout::add_to_linker(&mut linker, |x| x).expect("Unable to add cli stdout");
Expand Down

0 comments on commit f6f7de8

Please sign in to comment.