Skip to content

Add gloo-net crate #191

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

Merged
merged 37 commits into from
Feb 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
023f703
Initial commit
ranile Jan 14, 2021
6dc24dc
provide a better interface for errors, rename `RequestMethod` to `Met…
ranile Jan 22, 2021
196736a
remove method for array buffer and blob in favor of as_raw
ranile Feb 3, 2021
b2fc172
prepare for release
ranile Feb 3, 2021
a66c877
add CI, update readme
ranile Feb 3, 2021
7fd401c
hide JsError in the docs
ranile Feb 3, 2021
408bd00
fix CI?
ranile Feb 3, 2021
1280c97
Install wasm-pack in CI
ranile Feb 3, 2021
f418266
misc
ranile Apr 25, 2021
35828ec
websocket API
ranile Apr 25, 2021
cf25cd3
add tests for websocket
ranile Apr 26, 2021
f8495ae
update documentation, prepare for release
ranile Apr 26, 2021
75cab89
fix mistake in documentation
ranile Apr 26, 2021
7866f5e
Rewrite WebSockets code (#4)
ranile Sep 1, 2021
fe1036f
deserialize Blob to Vec<u8> (#9)
mhuesch Oct 26, 2021
c0f2c6d
Update to Rust 2021 and use JsError from gloo-utils (#10)
ranile Oct 26, 2021
fb35677
Add response.binary method to obtain response as Vec<u8>
ranile Oct 29, 2021
445e9a5
Remove `Clone` impl from WebSocket.
ranile Nov 12, 2021
7bf2d38
Rustfmt + ignore editor config files
ranile Nov 12, 2021
f6531f5
Fix onclose handling (#14)
shenek Nov 15, 2021
c5d3e12
feat: feature gate json, websocket and http; enable them by default (…
yusdacra Nov 18, 2021
22164e9
0.3.0
ranile Nov 19, 2021
8d0be9d
Fix outdated/missing docs
ranile Nov 21, 2021
5bf1c88
0.3.1
ranile Nov 21, 2021
c62e8cb
Change edition from 2021 to 2018 (#18)
lukechu10 Dec 2, 2021
863668a
hopefully this will fix the issue (#19)
ranile Dec 16, 2021
1a64fb9
There's no message
ranile Dec 16, 2021
785b093
Replace `async-broadcast` with `futures-channel::mpsc` (#21)
ranile Dec 24, 2021
b4f0272
Release 0.4.0
ranile Dec 24, 2021
3100e91
Fix message ordering not being preserved (#29)
e00E Feb 9, 2022
5766120
0.4.1
ranile Feb 9, 2022
c2c47bb
move files for gloo merge
ranile Feb 15, 2022
9cc8722
remove licence files
ranile Feb 15, 2022
752e5b6
Merge remote-tracking branch 'hamza1311/reqwasm/gloo-reqwasm' into gl…
ranile Feb 15, 2022
f2d38a0
gloo-specific patches
ranile Feb 15, 2022
5fb431e
fix CI
ranile Feb 15, 2022
54a66f2
re-export net from gloo
ranile Feb 15, 2022
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
55 changes: 54 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --all
args: --workspace --exclude gloo-net

browser_tests:
name: Browser Tests
Expand Down Expand Up @@ -63,6 +63,59 @@ jobs:
- name: Run tests
run: |
for x in $(ls crates); do
# gloo-net is tested separately
if [[ "$x" == "net" ]]; then
continue
fi
wasm-pack test --headless --firefox --chrome crates/$x --all-features
wasm-pack test --headless --firefox --chrome crates/$x --no-default-features
done

test-net:
name: Test gloo-net
runs-on: ubuntu-latest
services:
httpbin:
image: kennethreitz/httpbin@sha256:599fe5e5073102dbb0ee3dbb65f049dab44fa9fc251f6835c9990f8fb196a72b
ports:
- 8080:80
echo_server:
image: jmalloc/echo-server@sha256:c461e7e54d947a8777413aaf9c624b4ad1f1bac5d8272475da859ae82c1abd7d
ports:
- 8081:8080

steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
components: clippy
target: wasm32-unknown-unknown

- name: Install wasm-pack
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: cargo-${{ runner.os }}-test-${{ hashFiles('**/Cargo.toml') }}
restore-keys: |
cargo-${{ runner.os }}-test-
cargo-${{ runner.os }}-
- name: Run browser tests
env:
HTTPBIN_URL: "http://localhost:8080"
ECHO_SERVER_URL: "ws://localhost:8081"
run: wasm-pack test --chrome --firefox --headless

- name: Run browser tests
env:
HTTPBIN_URL: "http://localhost:8080"
ECHO_SERVER_URL: "ws://localhost:8081"
uses: actions-rs/cargo@v1
with:
command: test
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ gloo-console = { version = "0.2.1", path = "crates/console" }
gloo-utils = { version = "0.1.1", path = "crates/utils" }
gloo-history = { version = "0.1.0", path = "crates/history" }
gloo-worker = { version = "0.1.0", path = "crates/worker" }
gloo-net = { path = "crates/net" }

[features]
default = []
Expand All @@ -41,4 +42,5 @@ members = [
"crates/utils",
"crates/history",
"crates/worker",
"crates/net",
]
75 changes: 75 additions & 0 deletions crates/net/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
[package]
name = "gloo-net"
version = "0.1.0"
authors = ["Rust and WebAssembly Working Group", "Muhammad Hamza <[email protected]>"]
edition = "2018"
license = "MIT OR Apache-2.0"
repository = "https://github.com/hamza1311/reqwasm"
description = "HTTP requests library for WASM Apps"
readme = "README.md"
keywords = ["requests", "http", "wasm", "websockets"]
categories = ["wasm", "web-programming::http-client", "api-bindings"]

[package.metadata.docs.rs]
all-features = true

[dependencies]
wasm-bindgen = "0.2"
web-sys = "0.3"
js-sys = "0.3"
gloo-utils = { version = "0.1", path = "../utils" }

wasm-bindgen-futures = "0.4"
futures-core = { version = "0.3", optional = true }
futures-sink = { version = "0.3", optional = true }

thiserror = "1.0"

serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true }

futures-channel = { version = "0.3", optional = true }
pin-project = { version = "1.0", optional = true }

[dev-dependencies]
wasm-bindgen-test = "0.3"
futures = "0.3"

[features]
default = ["json", "websocket", "http"]

# Enables `.json()` on `Response`
json = ["wasm-bindgen/serde-serialize", "serde", "serde_json"]
# Enables the WebSocket API
websocket = [
'web-sys/WebSocket',
'web-sys/ErrorEvent',
'web-sys/FileReader',
'web-sys/MessageEvent',
'web-sys/ProgressEvent',
'web-sys/CloseEvent',
'web-sys/BinaryType',
'web-sys/Blob',
"futures-channel",
"pin-project",
"futures-core",
"futures-sink",
]
# Enables the HTTP API
http = [
'web-sys/Headers',
'web-sys/Request',
'web-sys/RequestInit',
'web-sys/RequestMode',
'web-sys/Response',
'web-sys/Window',
'web-sys/RequestCache',
'web-sys/RequestCredentials',
'web-sys/ObserverCallback',
'web-sys/RequestRedirect',
'web-sys/ReferrerPolicy',
'web-sys/AbortSignal',
'web-sys/ReadableStream',
'web-sys/Blob',
'web-sys/FormData',
]
57 changes: 57 additions & 0 deletions crates/net/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<div align="center">

<h1><code>gloo-net</code></h1>

<p>
<a href="https://crates.io/crates/gloo-net"><img src="https://img.shields.io/crates/v/gloo-net.svg?style=flat-square" alt="Crates.io version" /></a>
<a href="https://crates.io/crates/gloo-net"><img src="https://img.shields.io/crates/d/gloo-net.svg?style=flat-square" alt="Download" /></a>
<a href="https://docs.rs/gloo-net"><img src="https://img.shields.io/badge/docs-latest-blue.svg?style=flat-square" alt="docs.rs docs" /></a>
</p>

<h3>
<a href="https://docs.rs/gloo-net">API Docs</a>
<span> | </span>
<a href="https://github.com/rustwasm/gloo/blob/master/CONTRIBUTING.md">Contributing</a>
<span> | </span>
<a href="https://discordapp.com/channels/442252698964721669/443151097398296587">Chat</a>
</h3>

<sub>Built with 🦀🕸 by <a href="https://rustwasm.github.io/">The Rust and WebAssembly Working Group</a></sub>
</div>

HTTP requests library for WASM Apps. It provides idiomatic Rust bindings for the `web_sys` `fetch` and `WebSocket` API

## Examples

### HTTP

```rust
let resp = Request::get("/path")
.send()
.await
.unwrap();
assert_eq!(resp.status(), 200);
```

### WebSocket

```rust
use reqwasm::websocket::{Message, futures::WebSocket};
use wasm_bindgen_futures::spawn_local;
use futures::{SinkExt, StreamExt};

let mut ws = WebSocket::open("wss://echo.websocket.org").unwrap();
let (mut write, mut read) = ws.split();

spawn_local(async move {
write.send(Message::Text(String::from("test"))).await.unwrap();
write.send(Message::Text(String::from("test 2"))).await.unwrap();
});

spawn_local(async move {
while let Some(msg) = read.next().await {
console_log!(format!("1. {:?}", msg))
}
console_log!("WebSocket Closed")
})
```
40 changes: 40 additions & 0 deletions crates/net/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use gloo_utils::errors::JsError;
use thiserror::Error as ThisError;

/// All the errors returned by this crate.
#[derive(Debug, ThisError)]
pub enum Error {
/// Error returned by JavaScript.
#[error("{0}")]
JsError(JsError),
/// Error returned by `serde` during deserialization.
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
#[error("{0}")]
SerdeError(
#[source]
#[from]
serde_json::Error,
),
}

#[cfg(any(feature = "http", feature = "websocket"))]
pub(crate) use conversion::*;
#[cfg(any(feature = "http", feature = "websocket"))]
mod conversion {
use gloo_utils::errors::JsError;
use std::convert::TryFrom;
use wasm_bindgen::JsValue;

#[cfg(feature = "http")]
pub(crate) fn js_to_error(js_value: JsValue) -> super::Error {
super::Error::JsError(js_to_js_error(js_value))
}

pub(crate) fn js_to_js_error(js_value: JsValue) -> JsError {
match JsError::try_from(js_value) {
Ok(error) => error,
Err(_) => unreachable!("JsValue passed is not an Error type -- this is a bug"),
}
}
}
Loading