Skip to content

Commit

Permalink
Fix http request for wasm
Browse files Browse the repository at this point in the history
  • Loading branch information
vemonet committed Dec 15, 2023
1 parent 6d1c0f0 commit e772c35
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 61 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ jobs:
cache-dependency-path: '**/requirements.dev.txt'
- run: pip install -r python/requirements.dev.txt
- run: maturin build --release -m python/Cargo.toml
- run: pip install --no-index --find-links=target/wheels/ curies
- run: pip install --no-index --find-links=target/wheels/ curies-rs
- run: rm -r target/wheels
- run: maturin build --release --target universal2-apple-darwin -m python/Cargo.toml
- run: maturin build --release -m python/Cargo.toml
Expand Down Expand Up @@ -170,7 +170,7 @@ jobs:
- run: Remove-Item -LiteralPath "C:\msys64\" -Force -Recurse
- run: pip install -r python/requirements.dev.txt
- run: maturin build --release -m python/Cargo.toml
- run: pip install --no-index --find-links=target/wheels/ curies
- run: pip install --no-index --find-links=target/wheels/ curies-rs
- run: rm -r target/wheels
- run: maturin build --release -m python/Cargo.toml
- run: maturin sdist -m python/Cargo.toml
Expand Down
22 changes: 0 additions & 22 deletions .github/workflows/rust.yml

This file was deleted.

10 changes: 6 additions & 4 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ jobs:
test:
name: 🧪 Tests
runs-on: ubuntu-latest
env:
CARGO_TERM_COLOR: always
steps:
- uses: actions/checkout@v4
with:
Expand All @@ -42,10 +44,10 @@ jobs:
run: |
cargo tarpaulin -p curies --out xml --verbose --timeout 120
# - name: Upload to codecov.io
# uses: codecov/codecov-action@v2
# with:
# fail_ci_if_error: true
- name: Upload to codecov.io
uses: codecov/codecov-action@v2
with:
fail_ci_if_error: false
# token: ${{secrets.CODECOV_TOKEN}}

# docs:
Expand Down
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,24 @@
# 🦀 curies.rs
<h1 align="center">
🦀 curies.rs
</h1>

<p align="center">
<a href="https://github.com/biopragmatics/curies.rs/actions/workflows/test.yml">
<img alt="Test" src="https://github.com/biopragmatics/curies.rs/actions/workflows/test.yml/badge.svg" />
</a>
<a href="https://github.com/biopragmatics/curies.rs/actions/workflows/build.yml">
<img alt="Build" src="https://github.com/biopragmatics/curies.rs/actions/workflows/build.yml/badge.svg" />
</a>
<a href="https://deps.rs/repo/github/biopragmatics/curies.rs">
<img src="https://deps.rs/repo/github/biopragmatics/curies.rs/status.svg" alt="Dependency status" />
</a>
<a href="https://github.com/biopragmatics/curies.rs/blob/main/LICENSE">
<img alt="MIT license" src="https://img.shields.io/badge/License-MIT-brightgreen.svg" />
</a>
<!-- a href="https://codecov.io/gh/biopragmatics/curies.rs/branch/main">
<img src="https://codecov.io/gh/biopragmatics/curies.rs/branch/main/graph/badge.svg" alt="Codecov status" />
</a -->
</p>

Idiomatic conversion between URIs and compact URIs (CURIEs) in Rust.

Expand Down
12 changes: 7 additions & 5 deletions js/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<p id="expanded"></p>

<script type="module">
import init, { Record, Converter } from "./pkg/web.js";
import init, { Record, Converter, getOboConverter } from "./pkg/web.js";

async function main() {
await init();
Expand All @@ -25,11 +25,13 @@
// uri_prefix_synonyms: [],
// };

const converter = new Converter();
converter.addRecord(rec1);
// const converter = new Converter();
// converter.addRecord(rec1);

const compressedUri = converter.compress("http://purl.obolibrary.org/obo/DOID_");
const expandedUri = converter.expand("doid:1234");
const converter = await getOboConverter();

const compressedUri = converter.compress("http://purl.obolibrary.org/obo/DOID_1234");
const expandedUri = converter.expand("DOID:1234");
document.getElementById("compressed").innerText = compressedUri;
document.getElementById("expanded").innerText = expandedUri;
}
Expand Down
23 changes: 16 additions & 7 deletions js/src/curies.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::collections::HashSet;

use curies::{Converter, Record};
// use js_sys::{Promise, JSON};
use curies::{sources::get_obo_converter, Converter, Record};
use js_sys::Promise;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::future_to_promise;

#[wasm_bindgen(js_name = Record )]
#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -84,13 +85,21 @@ impl ConverterJs {

// #[wasm_bindgen(js_name = prefixMap)]
// pub fn prefix_map(&self) -> Result<JsValue, JsValue> {
// serde_wasm_bindgen::to_value(&self.converter).map_err(|e| e.into())
// serde_wasm_bindgen::to_value(&self.converter.prefix_map).map_err(|e| e.into())
// }
}

// #[wasm_bindgen(js_name = toString)]
// pub fn to_string(&self) -> String {
// self.converter.to_string()
// }
/// Get OBO converter
#[wasm_bindgen(js_name = getOboConverter)]
pub fn get_obo_converter_js() -> Promise {
future_to_promise(async move {
match get_obo_converter().await {
Ok(converter) => Ok(JsValue::from(ConverterJs { converter })),
Err(e) => Err(JsValue::from_str(&format!(
"Error getting OBO converter: {e}"
))),
}
})
}

// impl Into<JsValue> for RecordJs {
Expand Down
1 change: 0 additions & 1 deletion lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ serde_json = "1.0"
reqwest = { version = "0.11", features = ["blocking", "json"] }
async-trait = "0.1"


[dev-dependencies]
tokio = { version = "1.34", features = ["rt-multi-thread", "macros"] }

Expand Down
4 changes: 3 additions & 1 deletion lib/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ use std::error::Error;
use std::fmt;
use std::str::Utf8Error;

use serde::Deserialize;

/// Enum of errors returned by this library
#[derive(Debug)]
#[derive(Debug, Deserialize)]
pub enum CuriesError {
NotFound(String),
InvalidCurie(String),
Expand Down
35 changes: 17 additions & 18 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,17 +250,18 @@ impl Default for Converter {
}

/// Trait to provide the data as URL, HashMap, string, or Path to file
#[async_trait]
pub trait DataSource {
// FutureExt::shared
#[async_trait(?Send)]
pub trait DataSource: Send + Sync {
async fn fetch(self) -> Result<HashMap<String, Value>, CuriesError>;
}
#[async_trait]
#[async_trait(?Send)]
impl DataSource for HashMap<String, Value> {
async fn fetch(self) -> Result<HashMap<String, Value>, CuriesError> {
Ok(self)
}
}
#[async_trait]
#[async_trait(?Send)]
impl DataSource for HashMap<String, String> {
async fn fetch(self) -> Result<HashMap<String, Value>, CuriesError> {
Ok(self
Expand All @@ -269,33 +270,31 @@ impl DataSource for HashMap<String, String> {
.collect())
}
}
#[async_trait]
#[async_trait(?Send)]
impl DataSource for &str {
async fn fetch(self) -> Result<HashMap<String, Value>, CuriesError> {
if self.starts_with("https://") || self.starts_with("http://") || self.starts_with("ftp://")
{
// Making an HTTP request
let res = reqwest::get(self).await?;
if res.status().is_success() {
return Ok(res.json().await?);
} else {
return Err(CuriesError::Reqwest(format!(
"{}: {}",
res.status(),
res.text().await?
)));
}
// Get URL content with HTTP request
let client = reqwest::Client::new();
Ok(client
.get(self)
.header(reqwest::header::ACCEPT, "application/json")
.send()
.await?
.json()
.await?)
} else {
// Directly parsing the provided string as JSON
Ok(serde_json::from_str(self)?)
}
}
}
#[async_trait]
#[async_trait(?Send)]
impl DataSource for &Path {
async fn fetch(self) -> Result<HashMap<String, Value>, CuriesError> {
if self.exists() {
// Reading from a file path
// Read from a file path
let mut file = File::open(self)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Expand Down

0 comments on commit e772c35

Please sign in to comment.