Skip to content

Commit

Permalink
Implemented axios get method for simple url
Browse files Browse the repository at this point in the history
  • Loading branch information
redoC-A2k committed May 24, 2024
1 parent 2bd6b57 commit 35a2faf
Show file tree
Hide file tree
Showing 12 changed files with 222 additions and 11 deletions.
2 changes: 2 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/axios/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
node_modules/
3 changes: 3 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/axios/axios/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import axios from "axios";

const axios = axios;
20 changes: 20 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/axios/axios/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "axios",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "1.7.0-beta.2",
"webpack": "^5.91.0"
},
"devDependencies": {
"webpack-cli": "^5.1.4"
}
}
16 changes: 16 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/axios/axios/webpack.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { optimize } = require('webpack');
const webpack = require('webpack');

const config = {
entry: './index.js',
output: {
path: __dirname + '/dist',
filename: 'index.js',
iife:false
},
optimization:{
minimize:false
}
}

module.exports = config;
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 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();
context.eval_global("axios.js", include_str!("axios/dist/index.js"))?;
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,
));
println!("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)
}
}
15 changes: 4 additions & 11 deletions JS/wasm/crates/arakoo-core/src/apis/fetch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ use super::{
APIConfig, JSApiSet,
};
use javy::quickjs::{JSContextRef, JSValue, JSValueRef};
use quickjs_wasm_rs::{from_qjs_value, Deserializer, Serializer};
use quickjs_wasm_rs::{from_qjs_value, to_qjs_value, Deserializer, Serializer};
use serde::{Deserialize, Serialize};
use std::ops::Deref;
use std::str;
use std::sync::mpsc;
use std::time::Duration;
use std::{str, thread};

mod outbound_http;

Expand All @@ -30,21 +32,12 @@ impl JSApiSet for Fetch {
},
)?,
)?;
// global
// .set_property(
// "setTimeout",
// context
// .wrap_callback(set_timeout_api())
// .expect("unable to get result"),
// )
// .expect("unable to set property");

Ok(())
}
}



fn send_http_request(
context: &JSContextRef,
_this: &JSValueRef,
Expand Down
2 changes: 2 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/http/shims/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Url from "url-parse";
import _queryString from "query-string";
import "fast-text-encoding"

let __require_map = {}

// let encoder = new TextEncoder()
let decoder = new TextDecoder()
Expand Down Expand Up @@ -332,6 +333,7 @@ class Response {
// return Promise.resolve(new Response(response.body, response));
// };


function encodeBody(body) {
if (typeof (body) == "string") {
return encoder.encode(body).buffer
Expand Down
2 changes: 2 additions & 0 deletions JS/wasm/crates/arakoo-core/src/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ mod text_encoding;
mod pdfparse;
mod fetch;
mod jsonnet;
mod axios;
pub(crate) trait JSApiSet {
fn register(&self, runtime: &Runtime, config: &APIConfig) -> Result<()>;
}
Expand All @@ -86,5 +87,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(())
}
51 changes: 51 additions & 0 deletions JS/wasm/examples/axios/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { build } from "esbuild";
import fs from "fs";
let runtime = process.argv[2];

// let jsonnetLoadPlugin = {
// name: "jsonnet-load",
// setup(build) {
// build.onLoad({ filter: /\.jsonnet$/ }, async (args) => {
// let code = await fs.promises.readFile(args.path, "utf-8");
// return {
// contents: code,
// loader: "text",
// };
// })
// }
// }


build({
entryPoints: ["src/index.js"],
// entryPoints: ["src/index.js"],
bundle: true,
// minify: true,
minifySyntax: true,
outfile: "bin/app.js",
// outdir: "bin",
// inject:["shim.js"],
// define:{
// "export":"_export"
// },
format: "cjs",
target: "esnext",
external: ["axios"],
// banner: {
// js: `
// function require (name) {
// console.log("Requiring",name)
// return __require_map[name];
// }`
// },
platform: "node",
loader: {
".jsonnet": "copy",
},
define: {
"process.env.arakoo": JSON.stringify(runtime === "arakoo"),
},
}).catch((error) => {
console.error(error);
process.exit(1);
});
24 changes: 24 additions & 0 deletions JS/wasm/examples/axios/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "axios",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@vespaiach/axios-fetch-adapter": "^0.3.1",
"axios": "1.7.0-beta.2",
"hono": "^3.9",
"javy": "^0.1.2"
},
"devDependencies": {
"esbuild": "^0.21.3",
"webpack": "^5.91.0",
"webpack-cli": "^5.1.4"
},
"type": "module"
}
41 changes: 41 additions & 0 deletions JS/wasm/examples/axios/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Hono } from "hono";
const app = new Hono();
import { writeFileSync, STDIO } from "javy/fs"

app.get("/", (c) => {
console.log("axios")
return c.text("Hello World!");
});

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

app.get("/axios", async (c) => {
console.log("In axios")
let result = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
let json = result.data;
return c.json(json);
})

app.get("/fetch", async (c) => {
try {
let result = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let body = await result.json()
return c.json(body);
} catch (error) {
console.log("Error occured - ")
writeOutput(error);
console.log(error);
return c.json(error)
}

})

globalThis._export = app;

// let result = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
// let json = result.data;
// console.log(json);
Binary file not shown.

0 comments on commit 35a2faf

Please sign in to comment.