├── .github └── workflows │ ├── ci.yaml │ └── deploy-page.yaml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── dist └── index.html ├── examples ├── ipinfo.rs ├── observer.rs ├── typed.rs └── window.rs └── src ├── lib.rs ├── prelude.rs └── typed.rs /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main,master] 6 | pull_request: 7 | branches: [main,master] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | # Run cargo test 14 | test: 15 | name: Test Suite 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout sources 19 | uses: actions/checkout@v2 20 | - name: Cache 21 | uses: actions/cache@v4 22 | with: 23 | path: | 24 | ~/.cargo/bin/ 25 | ~/.cargo/registry/index/ 26 | ~/.cargo/registry/cache/ 27 | ~/.cargo/git/db/ 28 | target/ 29 | key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.toml') }} 30 | - name: Install stable toolchain 31 | uses: actions-rs/toolchain@v1 32 | with: 33 | profile: minimal 34 | toolchain: stable 35 | override: true 36 | - name: Install Dependencies 37 | run: sudo apt-get update; sudo apt-get install pkg-config libx11-dev libasound2-dev libudev-dev libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev 38 | - name: Run cargo test 39 | uses: actions-rs/cargo@v1 40 | with: 41 | command: test 42 | 43 | # Run cargo clippy -- -D warnings 44 | clippy_check: 45 | name: Clippy 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: Checkout sources 49 | uses: actions/checkout@v2 50 | - name: Cache 51 | uses: actions/cache@v4 52 | with: 53 | path: | 54 | ~/.cargo/bin/ 55 | ~/.cargo/registry/index/ 56 | ~/.cargo/registry/cache/ 57 | ~/.cargo/git/db/ 58 | target/ 59 | key: ${{ runner.os }}-cargo-clippy-${{ hashFiles('**/Cargo.toml') }} 60 | - name: Install stable toolchain 61 | uses: actions-rs/toolchain@v1 62 | with: 63 | toolchain: stable 64 | profile: minimal 65 | components: clippy 66 | override: true 67 | - name: Install Dependencies 68 | run: sudo apt-get update; sudo apt-get install pkg-config libx11-dev libasound2-dev libudev-dev 69 | - name: Run clippy 70 | uses: actions-rs/clippy-check@v1 71 | with: 72 | token: ${{ secrets.GITHUB_TOKEN }} 73 | args: -- -D warnings 74 | 75 | # Run cargo fmt --all -- --check 76 | format: 77 | name: Format 78 | runs-on: ubuntu-latest 79 | steps: 80 | - name: Checkout sources 81 | uses: actions/checkout@v2 82 | - name: Install stable toolchain 83 | uses: actions-rs/toolchain@v1 84 | with: 85 | toolchain: stable 86 | profile: minimal 87 | components: rustfmt 88 | override: true 89 | - name: Run cargo fmt 90 | uses: actions-rs/cargo@v1 91 | with: 92 | command: fmt 93 | args: --all -- --check 94 | -------------------------------------------------------------------------------- /.github/workflows/deploy-page.yaml: -------------------------------------------------------------------------------- 1 | name: deploy-github-page 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | permissions: 7 | contents: write 8 | 9 | jobs: 10 | build-web: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout repository 15 | uses: actions/checkout@v4 16 | - name: Install rust toolchain 17 | uses: dtolnay/rust-toolchain@master 18 | with: 19 | toolchain: stable 20 | - name: Install Dependencies 21 | run: sudo apt-get update; sudo apt-get install pkg-config libx11-dev libasound2-dev libudev-dev 22 | # - name: Install trunk 23 | # uses: jetli/trunk-action@v0.4.0 24 | # with: 25 | # version: 'latest' 26 | - name: Install wasm-bindgen 27 | run: | 28 | cargo install wasm-bindgen-cli 29 | - name: Add wasm target 30 | run: | 31 | rustup target add wasm32-unknown-unknown 32 | - name: Build Example 33 | run: | 34 | cargo build --release --target wasm32-unknown-unknown --example window 35 | - name: Wasm bindgen 36 | run: | 37 | wasm-bindgen --no-typescript --target web --out-dir ./dist/ --out-name "httpclient" ./target/wasm32-unknown-unknown/release/examples/window.wasm 38 | - name: optimize Wasm 39 | uses: NiklasEi/wasm-opt-action@v2 40 | with: 41 | file: dist/*.wasm 42 | - name: Deploy to GitHub Pages 43 | uses: JamesIves/github-pages-deploy-action@v4.2.5 44 | with: 45 | branch: gh-pages 46 | folder: dist -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | /.idea 4 | /.vscode 5 | 6 | dist/httpclient.js 7 | dist/httpclient_bg.wasm -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [0.8.2] - 2025-06-03 4 | 5 | * access inner value T from a TypedResponse reference [#11](https://github.com/foxzool/bevy_http_client/pull/11) 6 | 7 | ## [0.8.1] 8 | 9 | - add component observe 10 | 11 | ## [0.8.0] 12 | 13 | - bump bevy version to 0.16.0 14 | 15 | ## [0.7.0] - 2024-11-30 16 | 17 | - bump bevy version to 0.15.0 18 | 19 | ## [0.6.0] - 2024-07-05 20 | 21 | - bump bevy version to 0.14.0 22 | 23 | ## [0.5.2] - 2024-04-23 24 | 25 | * Fix: extract inner type [#8](https://github.com/foxzool/bevy_http_client/issues/8) 26 | 27 | ## [0.5.1] - 2024-02-28 28 | 29 | * Fix: Typed error handling [#6](https://github.com/foxzool/bevy_http_client/pull/6) 30 | * Fix: use crossbeam-channel replace task for wasm error 31 | 32 | ## [0.5.0] - 2024-02-20 33 | 34 | - now it's use event to send request and handle response 35 | 36 | ## [0.4.0] - 2024-02-19 37 | 38 | - bump bevy version to 0.13.0 -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_http_client" 3 | description = "A simple HTTP client for Bevy" 4 | version = "0.8.2" 5 | edition = "2024" 6 | readme = "README.md" 7 | homepage = "https://crates.io/crates/bevy_http_client" 8 | documentation = "https://docs.rs/bevy_http_client" 9 | repository = "https://github.com/foxzool/bevy_http_client" 10 | authors = ["FoxZoOL "] 11 | license = "MIT OR Apache-2.0" 12 | keywords = ["bevy", "http", "plugin", "wasm"] 13 | 14 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 15 | 16 | [dependencies] 17 | bevy_app = "0.16.0" 18 | bevy_derive = "0.16.0" 19 | #bevy_hierarchy = "0.16.0" 20 | bevy_ecs = { version = "0.16.0", features = ["multi_threaded"] } 21 | bevy_tasks = "0.16.0" 22 | 23 | crossbeam-channel = "0.5.11" 24 | ehttp = { version = "0.5.0", features = ["native-async", "json"] } 25 | serde = { version = "1.0", features = ["derive"] } 26 | serde_json = "1.0" 27 | 28 | [lib] 29 | doctest = false 30 | 31 | [dev-dependencies] 32 | bevy = { version = "0.16.0", default-features = false, features = [ 33 | "animation", 34 | "bevy_asset", 35 | "bevy_gilrs", 36 | "bevy_scene", 37 | "bevy_winit", 38 | "bevy_core_pipeline", 39 | "bevy_pbr", 40 | "bevy_gltf", 41 | "bevy_render", 42 | "bevy_sprite", 43 | "bevy_text", 44 | "bevy_ui", 45 | "bevy_window", 46 | "bevy_log", 47 | "multi_threaded", 48 | "png", 49 | "hdr", 50 | "x11", 51 | "bevy_gizmos", 52 | "tonemapping_luts", 53 | "default_font", 54 | "webgl2", 55 | "sysinfo_plugin", 56 | ] } -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bevy_http_client 2 | 3 | [![CI](https://github.com/foxzool/bevy_http_client/workflows/CI/badge.svg)](https://github.com/foxzool/bevy_http_client/actions) 4 | [![Crates.io](https://img.shields.io/crates/v/bevy_http_client)](https://crates.io/crates/bevy_http_client) 5 | [![Downloads](https://img.shields.io/crates/d/bevy_http_client)](https://crates.io/crates/bevy_http_client) 6 | [![Documentation](https://docs.rs/bevy_http_client/badge.svg)](https://docs.rs/bevy_http_client) 7 | [![MIT/Apache 2.0](https://img.shields.io/badge/license-MIT%2FApache-blue.svg)](https://github.com/Seldom-SE/seldom_pixel#license) 8 | 9 | A simple HTTP client Bevy Plugin for both native and WASM. 10 | 11 | ## Example 12 | 13 | ```rust 14 | use bevy::{prelude::*, time::common_conditions::on_timer}; 15 | use bevy_http_client::prelude::*; 16 | use serde::Deserialize; 17 | 18 | #[derive(Debug, Clone, Deserialize, Default)] 19 | pub struct IpInfo { 20 | pub ip: String, 21 | } 22 | 23 | fn main() { 24 | let mut app = App::new(); 25 | app.add_plugins((MinimalPlugins, HttpClientPlugin)) 26 | .add_systems(Update, (handle_response, handle_error)) 27 | .add_systems( 28 | Update, 29 | send_request.run_if(on_timer(std::time::Duration::from_secs(1))), 30 | ); 31 | app.register_request_type::(); 32 | app.run(); 33 | } 34 | 35 | fn send_request(mut ev_request: EventWriter>) { 36 | ev_request.send( 37 | HttpClient::new() 38 | .get("https://api.ipify.org?format=json") 39 | .with_type::(), 40 | ); 41 | } 42 | 43 | /// consume TypedResponse events 44 | fn handle_response(mut events: ResMut>>) { 45 | for response in events.drain() { 46 | let response: IpInfo = response.into_inner(); 47 | println!("ip info: {:?}", response); 48 | } 49 | } 50 | 51 | fn handle_error(mut ev_error: EventReader>) { 52 | for error in ev_error.read() { 53 | println!("Error retrieving IP: {}", error.err); 54 | } 55 | } 56 | 57 | ``` 58 | 59 | ## Supported Versions 60 | 61 | | bevy | bevy_http_client | 62 | |------|------------------| 63 | | 0.16 | 0.8 | 64 | | 0.15 | 0.7 | 65 | | 0.14 | 0.6 | 66 | | 0.13 | 0.4, 0,5 | 67 | | 0.12 | 0.3 | 68 | | 0.11 | 0.1 | 69 | 70 | ## License 71 | 72 | Dual-licensed under either: 73 | 74 | - [`MIT`](LICENSE-MIT): [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT) 75 | - [`Apache 2.0`](LICENSE-APACHE): [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 76 | 77 | At your option. This means that when using this crate in your game, you may choose which license to use. 78 | 79 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as 80 | defined in the Apache-2.0 license, shall be dually licensed as above, without any additional terms or conditions. 81 | -------------------------------------------------------------------------------- /dist/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Bevy http client exmaple 7 | 8 | 9 | 18 | 19 | Javascript and support for canvas is required 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /examples/ipinfo.rs: -------------------------------------------------------------------------------- 1 | use bevy::{prelude::*, time::common_conditions::on_timer}; 2 | 3 | use bevy_http_client::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins((MinimalPlugins, HttpClientPlugin)) 8 | .add_systems(Update, (handle_response, handle_error)) 9 | .add_systems( 10 | Update, 11 | send_request.run_if(on_timer(std::time::Duration::from_secs(1))), 12 | ) 13 | .run(); 14 | } 15 | 16 | fn send_request(mut ev_request: EventWriter) { 17 | let request = HttpClient::new().get("https://api.ipify.org").build(); 18 | ev_request.write(request); 19 | } 20 | 21 | fn handle_response(mut ev_resp: EventReader) { 22 | for response in ev_resp.read() { 23 | println!("response: {:?}", response.text()); 24 | } 25 | } 26 | 27 | fn handle_error(mut ev_error: EventReader) { 28 | for error in ev_error.read() { 29 | println!("Error retrieving IP: {}", error.err); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/observer.rs: -------------------------------------------------------------------------------- 1 | use bevy::{prelude::*, time::common_conditions::on_timer}; 2 | 3 | use bevy_http_client::prelude::*; 4 | 5 | fn main() { 6 | App::new() 7 | .add_plugins((MinimalPlugins, HttpClientPlugin)) 8 | .add_systems(Startup, init_request) 9 | .add_systems( 10 | Update, 11 | send_request.run_if(on_timer(std::time::Duration::from_secs(1))), 12 | ) 13 | .run(); 14 | } 15 | 16 | #[derive(Component)] 17 | struct IpRequestMarker; 18 | 19 | fn init_request(mut commands: Commands) { 20 | let entity = commands.spawn(IpRequestMarker).id(); 21 | let request = HttpClient::new_with_entity(entity).get("https://api.ipify.org"); 22 | commands 23 | .entity(entity) 24 | .insert(request) 25 | .observe(handle_response) 26 | .observe(handle_error); 27 | } 28 | 29 | fn send_request( 30 | clients: Query<&HttpClient, With>, 31 | mut ev_request: EventWriter, 32 | ) { 33 | let requests = clients 34 | .iter() 35 | .map(|c| c.clone().build()) 36 | .collect::>(); 37 | 38 | ev_request.write_batch(requests); 39 | } 40 | 41 | fn handle_response(response: Trigger) { 42 | println!("response: {:?}", response.text()); 43 | } 44 | 45 | fn handle_error(error: Trigger) { 46 | println!("Error retrieving IP: {}", error.err); 47 | } 48 | -------------------------------------------------------------------------------- /examples/typed.rs: -------------------------------------------------------------------------------- 1 | use bevy::{prelude::*, time::common_conditions::on_timer}; 2 | use bevy_http_client::prelude::*; 3 | use serde::Deserialize; 4 | 5 | #[derive(Debug, Clone, Deserialize, Default)] 6 | pub struct IpInfo { 7 | pub ip: String, 8 | } 9 | 10 | fn main() { 11 | let mut app = App::new(); 12 | app.add_plugins((MinimalPlugins, HttpClientPlugin)) 13 | .add_systems(Update, (handle_response, handle_error)) 14 | .add_systems( 15 | Update, 16 | send_request.run_if(on_timer(std::time::Duration::from_secs(1))), 17 | ); 18 | app.register_request_type::(); 19 | app.run(); 20 | } 21 | 22 | fn send_request(mut ev_request: EventWriter>) { 23 | ev_request.write( 24 | HttpClient::new() 25 | .get("https://api.ipify.org?format=json") 26 | .with_type::(), 27 | ); 28 | } 29 | 30 | /// consume TypedResponse events 31 | fn handle_response(mut events: ResMut>>) { 32 | for response in events.drain() { 33 | let response: IpInfo = response.into_inner(); 34 | println!("ip info: {:?}", response); 35 | } 36 | } 37 | 38 | fn handle_error(mut ev_error: EventReader>) { 39 | for error in ev_error.read() { 40 | println!("Error retrieving IP: {}", error.err); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /examples/window.rs: -------------------------------------------------------------------------------- 1 | use bevy::{ 2 | color::palettes::css::{AQUA, LIME}, 3 | prelude::*, 4 | time::common_conditions::on_timer, 5 | }; 6 | use bevy_http_client::{ 7 | HttpClient, HttpClientPlugin, HttpRequest, HttpResponse, HttpResponseError, 8 | }; 9 | 10 | fn main() { 11 | App::new() 12 | .insert_resource(ClearColor(Color::srgb(0.4, 0.4, 0.4))) 13 | .add_plugins(DefaultPlugins.set(WindowPlugin { 14 | primary_window: Some(Window { 15 | title: "Wasm http request".to_string(), 16 | // Bind to canvas included in `index.html` 17 | canvas: Some("#bevy".to_owned()), 18 | // Tells wasm not to override default event handling, like F5 and Ctrl+R 19 | prevent_default_event_handling: false, 20 | ..default() 21 | }), 22 | ..default() 23 | })) 24 | .add_plugins(HttpClientPlugin) 25 | .add_systems(Startup, setup) 26 | .add_systems( 27 | Update, 28 | send_request.run_if(on_timer(std::time::Duration::from_secs(2))), 29 | ) 30 | .add_systems(Update, (handle_response, handle_error)) 31 | .run(); 32 | } 33 | 34 | #[derive(Component)] 35 | struct ResponseText; 36 | 37 | #[derive(Component)] 38 | struct ResponseIP; 39 | 40 | fn setup(mut commands: Commands) { 41 | // Camera 42 | commands.spawn((Camera2d, IsDefaultUiCamera)); 43 | commands 44 | .spawn(( 45 | Node { 46 | position_type: PositionType::Absolute, 47 | padding: UiRect::all(Val::Px(5.0)), 48 | display: Display::Grid, 49 | ..default() 50 | }, 51 | ZIndex(i32::MAX), 52 | BackgroundColor(Color::BLACK.with_alpha(0.75)), 53 | )) 54 | .with_children(|parent| { 55 | let text_font = TextFont { 56 | font_size: 40., 57 | ..default() 58 | }; 59 | parent.spawn(Node::default()).with_children(|parent| { 60 | parent.spawn(( 61 | Text::new("Status: "), 62 | TextColor(LIME.into()), 63 | text_font.clone(), 64 | )); 65 | parent.spawn(( 66 | Text::new(""), 67 | TextColor(AQUA.into()), 68 | text_font.clone(), 69 | ResponseText, 70 | )); 71 | }); 72 | parent.spawn(Node::default()).with_children(|parent| { 73 | parent.spawn((Text::new("Ip: "), TextColor(LIME.into()), text_font.clone())); 74 | parent.spawn(( 75 | Text::new(""), 76 | TextColor(AQUA.into()), 77 | text_font.clone(), 78 | ResponseIP, 79 | )); 80 | }); 81 | }); 82 | } 83 | 84 | fn send_request( 85 | mut ev_request: EventWriter, 86 | mut status_query: Query<&mut Text, (With, Without)>, 87 | mut ip_query: Query<&mut Text, (With, Without)>, 88 | ) { 89 | if let Ok(mut text) = status_query.single_mut() { 90 | text.0 = "Requesting ".to_string(); 91 | } 92 | if let Ok(mut ip) = ip_query.single_mut() { 93 | ip.0 = "".to_string(); 94 | } 95 | 96 | let request = HttpClient::new().get("https://api.ipify.org").build(); 97 | ev_request.write(request); 98 | } 99 | 100 | fn handle_response( 101 | mut ev_resp: EventReader, 102 | mut status_query: Query<&mut Text, (With, Without)>, 103 | mut ip_query: Query<&mut Text, (With, Without)>, 104 | ) { 105 | for response in ev_resp.read() { 106 | if let Ok(mut text) = status_query.single_mut() { 107 | text.0 = "Got ".to_string(); 108 | } 109 | if let Ok(mut ip) = ip_query.single_mut() { 110 | ip.0 = response.text().unwrap_or_default().to_string(); 111 | } 112 | } 113 | } 114 | fn handle_error(mut ev_error: EventReader) { 115 | for error in ev_error.read() { 116 | println!("Error retrieving IP: {}", error.err); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | 3 | use bevy_app::{App, Plugin, Update}; 4 | use bevy_derive::Deref; 5 | use bevy_ecs::{prelude::*, world::CommandQueue}; 6 | use bevy_tasks::IoTaskPool; 7 | use crossbeam_channel::{Receiver, Sender}; 8 | use ehttp::{Headers, Request, Response}; 9 | 10 | use crate::prelude::TypedRequest; 11 | 12 | pub mod prelude; 13 | mod typed; 14 | 15 | /// Plugin that provides support for send http request and handle response. 16 | /// 17 | /// # Example 18 | /// ``` 19 | /// use bevy::prelude::*; 20 | /// use bevy_http_client::prelude::*; 21 | /// 22 | /// App::new() 23 | /// .add_plugins(DefaultPlugins) 24 | /// .add_plugins(HttpClientPlugin).run(); 25 | /// ``` 26 | #[derive(Default)] 27 | pub struct HttpClientPlugin; 28 | 29 | impl Plugin for HttpClientPlugin { 30 | fn build(&self, app: &mut App) { 31 | if !app.world().contains_resource::() { 32 | app.init_resource::(); 33 | } 34 | app.add_event::(); 35 | app.add_event::(); 36 | app.add_event::(); 37 | app.add_systems(Update, (handle_request, handle_tasks)); 38 | } 39 | } 40 | 41 | /// The setting of http client. 42 | /// can set the max concurrent request. 43 | #[derive(Resource, Debug)] 44 | pub struct HttpClientSetting { 45 | /// max concurrent request 46 | pub client_limits: usize, 47 | current_clients: usize, 48 | } 49 | 50 | impl Default for HttpClientSetting { 51 | fn default() -> Self { 52 | Self { 53 | client_limits: 5, 54 | current_clients: 0, 55 | } 56 | } 57 | } 58 | 59 | impl HttpClientSetting { 60 | /// create a new http client setting 61 | pub fn new(max_concurrent: usize) -> Self { 62 | Self { 63 | client_limits: max_concurrent, 64 | current_clients: 0, 65 | } 66 | } 67 | 68 | /// check if the client is available 69 | #[inline] 70 | pub fn is_available(&self) -> bool { 71 | self.current_clients < self.client_limits 72 | } 73 | } 74 | 75 | #[derive(Event, Debug, Clone)] 76 | pub struct HttpRequest { 77 | pub from_entity: Option, 78 | pub request: Request, 79 | } 80 | 81 | /// builder for ehttp request 82 | #[derive(Component, Debug, Clone)] 83 | pub struct HttpClient { 84 | /// The entity that the request is associated with. 85 | from_entity: Option, 86 | /// "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", … 87 | method: Option, 88 | 89 | /// https://… 90 | url: Option, 91 | 92 | /// The data you send with e.g. "POST". 93 | body: Vec, 94 | 95 | /// ("Accept", "*/*"), … 96 | headers: Option, 97 | 98 | /// Request mode used on fetch. Only available on wasm builds 99 | #[cfg(target_arch = "wasm32")] 100 | pub mode: ehttp::Mode, 101 | } 102 | 103 | impl Default for HttpClient { 104 | fn default() -> Self { 105 | Self { 106 | from_entity: None, 107 | method: None, 108 | url: None, 109 | body: vec![], 110 | headers: Some(Headers::new(&[("Accept", "*/*")])), 111 | #[cfg(target_arch = "wasm32")] 112 | mode: ehttp::Mode::default(), 113 | } 114 | } 115 | } 116 | 117 | impl HttpClient { 118 | /// This method is used to create a new `HttpClient` instance. 119 | /// 120 | /// # Returns 121 | /// 122 | /// * `Self` - Returns the instance of the `HttpClient` struct. 123 | /// 124 | /// # Examples 125 | /// 126 | /// ``` 127 | /// let http_client = HttpClient::new(); 128 | /// ``` 129 | pub fn new() -> Self { 130 | Self::default() 131 | } 132 | 133 | /// his method is used to create a new `HttpClient` instance with `Entity`. 134 | /// 135 | /// # Arguments 136 | /// 137 | /// * `entity`: Target Entity 138 | /// 139 | /// returns: HttpClient 140 | /// 141 | /// # Examples 142 | /// 143 | /// ``` 144 | /// let e = commands.spawn().id(); 145 | /// let http_client = HttpClient::new_with_entity(e) 146 | /// ``` 147 | pub fn new_with_entity(entity: Entity) -> Self { 148 | Self { 149 | from_entity: Some(entity), 150 | ..Default::default() 151 | } 152 | } 153 | 154 | /// This method is used to create a `GET` HTTP request. 155 | /// 156 | /// # Arguments 157 | /// 158 | /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP 159 | /// request will be sent. 160 | /// 161 | /// # Returns 162 | /// 163 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 164 | /// 165 | /// # Examples 166 | /// 167 | /// ``` 168 | /// let http_client = HttpClient::new().get("http://example.com"); 169 | /// ``` 170 | pub fn get(mut self, url: impl ToString) -> Self { 171 | self.method = Some("GET".to_string()); 172 | self.url = Some(url.to_string()); 173 | self 174 | } 175 | 176 | /// This method is used to create a `POST` HTTP request. 177 | /// 178 | /// # Arguments 179 | /// 180 | /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP 181 | /// request will be sent. 182 | /// 183 | /// # Returns 184 | /// 185 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 186 | /// 187 | /// # Examples 188 | /// 189 | /// ``` 190 | /// let http_client = HttpClient::new().post("http://example.com"); 191 | /// ``` 192 | pub fn post(mut self, url: impl ToString) -> Self { 193 | self.method = Some("POST".to_string()); 194 | self.url = Some(url.to_string()); 195 | self 196 | } 197 | 198 | /// This method is used to create a `PUT` HTTP request. 199 | /// 200 | /// # Arguments 201 | /// 202 | /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP 203 | /// request will be sent. 204 | /// 205 | /// # Returns 206 | /// 207 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 208 | /// 209 | /// # Examples 210 | /// 211 | /// ``` 212 | /// let http_client = HttpClient::new().put("http://example.com"); 213 | /// ``` 214 | pub fn put(mut self, url: impl ToString) -> Self { 215 | self.method = Some("PUT".to_string()); 216 | self.url = Some(url.to_string()); 217 | self 218 | } 219 | 220 | /// This method is used to create a `PATCH` HTTP request. 221 | /// 222 | /// # Arguments 223 | /// 224 | /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP 225 | /// request will be sent. 226 | /// 227 | /// # Returns 228 | /// 229 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 230 | /// 231 | /// # Examples 232 | /// 233 | /// ``` 234 | /// let http_client = HttpClient::new().patch("http://example.com"); 235 | /// ``` 236 | pub fn patch(mut self, url: impl ToString) -> Self { 237 | self.method = Some("PATCH".to_string()); 238 | self.url = Some(url.to_string()); 239 | self 240 | } 241 | 242 | /// This method is used to create a `DELETE` HTTP request. 243 | /// 244 | /// # Arguments 245 | /// 246 | /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP 247 | /// request will be sent. 248 | /// 249 | /// # Returns 250 | /// 251 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 252 | /// 253 | /// # Examples 254 | /// 255 | /// ``` 256 | /// let http_client = HttpClient::new().delete("http://example.com"); 257 | /// ``` 258 | pub fn delete(mut self, url: impl ToString) -> Self { 259 | self.method = Some("DELETE".to_string()); 260 | self.url = Some(url.to_string()); 261 | self 262 | } 263 | 264 | /// This method is used to create a `HEAD` HTTP request. 265 | /// 266 | /// # Arguments 267 | /// 268 | /// * `url` - A value that can be converted into a string. This is the URL to which the HTTP 269 | /// request will be sent. 270 | /// 271 | /// # Returns 272 | /// 273 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 274 | /// 275 | /// # Examples 276 | /// 277 | /// ``` 278 | /// let http_client = HttpClient::new().head("http://example.com"); 279 | /// ``` 280 | pub fn head(mut self, url: impl ToString) -> Self { 281 | self.method = Some("HEAD".to_string()); 282 | self.url = Some(url.to_string()); 283 | self 284 | } 285 | 286 | /// This method is used to set the headers of the HTTP request. 287 | /// 288 | /// # Arguments 289 | /// 290 | /// * `headers` - A slice of tuples where each tuple represents a header. The first element of 291 | /// the tuple is the header name and the second element is the header value. 292 | /// 293 | /// # Returns 294 | /// 295 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 296 | /// 297 | /// # Examples 298 | /// 299 | /// ``` 300 | /// let http_client = HttpClient::new().post("http://example.com") 301 | /// .headers(&[("Content-Type", "application/json"), ("Accept", "*/*")]); 302 | /// ``` 303 | pub fn headers(mut self, headers: &[(&str, &str)]) -> Self { 304 | self.headers = Some(Headers::new(headers)); 305 | self 306 | } 307 | 308 | /// This method is used to set the body of the HTTP request as a JSON payload. 309 | /// It also sets the "Content-Type" header of the request to "application/json". 310 | /// 311 | /// # Arguments 312 | /// 313 | /// * `body` - A reference to any type that implements the `serde::Serialize` trait. This is the 314 | /// data that will be serialized to JSON and set as the body of the HTTP request. 315 | /// 316 | /// # Returns 317 | /// 318 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 319 | /// 320 | /// # Panics 321 | /// 322 | /// * This method will panic if the serialization of the `body` to JSON fails. 323 | /// 324 | /// # Examples 325 | /// 326 | /// ``` 327 | /// let http_client = HttpClient::new().post("http://example.com") 328 | /// .json(&data); 329 | /// ``` 330 | pub fn json(mut self, body: &impl serde::Serialize) -> Self { 331 | if let Some(headers) = self.headers.as_mut() { 332 | headers.insert("Content-Type".to_string(), "application/json".to_string()); 333 | } else { 334 | self.headers = Some(Headers::new(&[ 335 | ("Content-Type", "application/json"), 336 | ("Accept", "*/*"), 337 | ])); 338 | } 339 | 340 | self.body = serde_json::to_vec(body).unwrap(); 341 | self 342 | } 343 | 344 | /// This method is used to set the properties of the `HttpClient` instance using an `Request` 345 | /// instance. This version of the method is used when the target architecture is not 346 | /// `wasm32`. 347 | /// 348 | /// # Arguments 349 | /// 350 | /// * `request` - An instance of `Request` which includes the HTTP method, URL, body, and 351 | /// headers. 352 | /// 353 | /// # Returns 354 | /// 355 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 356 | /// 357 | /// # Examples 358 | /// 359 | /// ``` 360 | /// let request = Request { 361 | /// method: "POST".to_string(), 362 | /// url: "http://example.com".to_string(), 363 | /// body: vec![], 364 | /// headers: Headers::new(&[("Content-Type", "application/json"), ("Accept", "*/*")]), 365 | /// }; 366 | /// let http_client = HttpClient::new().request(request); 367 | /// ``` 368 | #[cfg(not(target_arch = "wasm32"))] 369 | pub fn request(mut self, request: Request) -> Self { 370 | self.method = Some(request.method); 371 | self.url = Some(request.url); 372 | self.body = request.body; 373 | self.headers = Some(request.headers); 374 | 375 | self 376 | } 377 | 378 | /// Associates an `Entity` with the `HttpClient`. 379 | /// 380 | /// This method is used to associate an `Entity` with the `HttpClient`. This can be useful when 381 | /// you want to track which entity initiated the HTTP request. 382 | /// 383 | /// # Parameters 384 | /// 385 | /// * `entity`: The `Entity` that you want to associate with the `HttpClient`. 386 | /// 387 | /// # Returns 388 | /// 389 | /// A mutable reference to the `HttpClient`. This is used to allow method chaining. 390 | /// 391 | /// # Examples 392 | /// 393 | /// ``` 394 | /// let entity = commands.spawn().id(); 395 | /// let http_client = HttpClient::new().entity(entity); 396 | /// ``` 397 | pub fn entity(mut self, entity: Entity) -> Self { 398 | self.from_entity = Some(entity); 399 | self 400 | } 401 | 402 | /// This method is used to set the properties of the `HttpClient` instance using an `Request` 403 | /// instance. This version of the method is used when the target architecture is `wasm32`. 404 | /// 405 | /// # Arguments 406 | /// 407 | /// * `request` - An instance of `Request` which includes the HTTP method, URL, body, headers, 408 | /// and mode. 409 | /// 410 | /// # Returns 411 | /// 412 | /// * `Self` - Returns the instance of the `HttpClient` struct, allowing for method chaining. 413 | /// 414 | /// # Examples 415 | /// 416 | /// ``` 417 | /// let request = Request { 418 | /// method: "POST".to_string(), 419 | /// url: "http://example.com".to_string(), 420 | /// body: vec![], 421 | /// headers: Headers::new(&[("Content-Type", "application/json"), ("Accept", "*/*")]), 422 | /// mode: Mode::Cors, 423 | /// }; 424 | /// let http_client = HttpClient::new().request(request); 425 | /// ``` 426 | #[cfg(target_arch = "wasm32")] 427 | pub fn request(mut self, request: Request) -> Self { 428 | self.method = Some(request.method); 429 | self.url = Some(request.url); 430 | self.body = request.body; 431 | self.headers = Some(request.headers); 432 | self.mode = request.mode; 433 | 434 | self 435 | } 436 | 437 | /// Builds an `HttpRequest` from the `HttpClient` instance. 438 | /// 439 | /// This method is used to construct an `HttpRequest` from the current state of the `HttpClient` 440 | /// instance. The resulting `HttpRequest` includes the HTTP method, URL, body, headers, and mode 441 | /// (only available on wasm builds). 442 | /// 443 | /// # Returns 444 | /// 445 | /// An `HttpRequest` instance which includes the HTTP method, URL, body, headers, and mode (only 446 | /// available on wasm builds). 447 | /// 448 | /// # Panics 449 | /// 450 | /// This method will panic if the HTTP method, URL, or headers are not set in the `HttpClient` 451 | /// instance. 452 | /// 453 | /// # Examples 454 | /// 455 | /// ``` 456 | /// let http_request = HttpClient::new().post("http://example.com") 457 | /// .headers(&[("Content-Type", "application/json"), ("Accept", "*/*")]) 458 | /// .json(&data) 459 | /// .build(); 460 | /// ``` 461 | /// 462 | /// # Note 463 | /// 464 | /// This method consumes the `HttpClient` instance, meaning it can only be called once per 465 | /// instance. 466 | pub fn build(self) -> HttpRequest { 467 | HttpRequest { 468 | from_entity: self.from_entity, 469 | request: Request { 470 | method: self.method.expect("method is required"), 471 | url: self.url.expect("url is required"), 472 | body: self.body, 473 | headers: self.headers.expect("headers is required"), 474 | #[cfg(target_arch = "wasm32")] 475 | mode: self.mode, 476 | }, 477 | } 478 | } 479 | 480 | pub fn with_type serde::Deserialize<'a>>(self) -> TypedRequest { 481 | TypedRequest::new( 482 | Request { 483 | method: self.method.expect("method is required"), 484 | url: self.url.expect("url is required"), 485 | body: self.body, 486 | headers: self.headers.expect("headers is required"), 487 | #[cfg(target_arch = "wasm32")] 488 | mode: self.mode, 489 | }, 490 | self.from_entity, 491 | ) 492 | } 493 | } 494 | 495 | /// wrap for ehttp response 496 | #[derive(Event, Debug, Clone, Deref)] 497 | pub struct HttpResponse(pub Response); 498 | 499 | /// wrap for ehttp error 500 | #[derive(Event, Debug, Clone, Deref)] 501 | pub struct HttpResponseError { 502 | pub err: String, 503 | } 504 | 505 | impl HttpResponseError { 506 | pub fn new(err: String) -> Self { 507 | Self { err } 508 | } 509 | } 510 | 511 | /// task for ehttp response result 512 | #[derive(Component, Debug)] 513 | pub struct RequestTask { 514 | tx: Sender, 515 | rx: Receiver, 516 | } 517 | 518 | fn handle_request( 519 | mut commands: Commands, 520 | mut req_res: ResMut, 521 | mut requests: EventReader, 522 | q_tasks: Query<&RequestTask>, 523 | ) { 524 | let thread_pool = IoTaskPool::get(); 525 | for request in requests.read() { 526 | if req_res.is_available() { 527 | let req = request.clone(); 528 | let (entity, has_from_entity) = if let Some(entity) = req.from_entity { 529 | (entity, true) 530 | } else { 531 | (commands.spawn_empty().id(), false) 532 | }; 533 | 534 | let tx = get_channel(&mut commands, q_tasks, entity); 535 | 536 | thread_pool 537 | .spawn(async move { 538 | let mut command_queue = CommandQueue::default(); 539 | 540 | let response = ehttp::fetch_async(req.request).await; 541 | command_queue.push(move |world: &mut World| { 542 | match response { 543 | Ok(res) => { 544 | world 545 | .get_resource_mut::>() 546 | .unwrap() 547 | .send(HttpResponse(res.clone())); 548 | world.trigger_targets(HttpResponse(res), entity); 549 | } 550 | Err(e) => { 551 | world 552 | .get_resource_mut::>() 553 | .unwrap() 554 | .send(HttpResponseError::new(e.to_string())); 555 | world 556 | .trigger_targets(HttpResponseError::new(e.to_string()), entity); 557 | } 558 | } 559 | 560 | if !has_from_entity { 561 | world.entity_mut(entity).despawn(); 562 | } 563 | }); 564 | 565 | tx.send(command_queue).unwrap(); 566 | }) 567 | .detach(); 568 | 569 | req_res.current_clients += 1; 570 | } 571 | } 572 | } 573 | 574 | fn get_channel( 575 | commands: &mut Commands, 576 | q_tasks: Query<&RequestTask>, 577 | entity: Entity, 578 | ) -> Sender { 579 | if let Ok(task) = q_tasks.get(entity) { 580 | task.tx.clone() 581 | } else { 582 | let (tx, rx) = crossbeam_channel::bounded(5); 583 | 584 | commands.entity(entity).insert(RequestTask { 585 | tx: tx.clone(), 586 | rx: rx.clone(), 587 | }); 588 | 589 | tx 590 | } 591 | } 592 | 593 | fn handle_tasks( 594 | mut commands: Commands, 595 | mut req_res: ResMut, 596 | mut request_tasks: Query<&RequestTask>, 597 | ) { 598 | for task in request_tasks.iter_mut() { 599 | if let Ok(mut command_queue) = task.rx.try_recv() { 600 | commands.append(&mut command_queue); 601 | req_res.current_clients -= 1; 602 | } 603 | } 604 | } 605 | -------------------------------------------------------------------------------- /src/prelude.rs: -------------------------------------------------------------------------------- 1 | pub use super::{ 2 | HttpClient, HttpClientPlugin, HttpClientSetting, HttpRequest, HttpResponse, HttpResponseError, 3 | RequestTask, 4 | typed::{HttpTypedRequestTrait, TypedRequest, TypedResponse, TypedResponseError}, 5 | }; 6 | -------------------------------------------------------------------------------- /src/typed.rs: -------------------------------------------------------------------------------- 1 | use bevy_app::{App, PreUpdate}; 2 | use bevy_derive::Deref; 3 | use bevy_ecs::{prelude::*, system::Commands, world::CommandQueue}; 4 | use bevy_tasks::IoTaskPool; 5 | use ehttp::{Request, Response}; 6 | use serde::Deserialize; 7 | use std::marker::PhantomData; 8 | 9 | use crate::{HttpClientSetting, RequestTask, get_channel}; 10 | 11 | pub trait HttpTypedRequestTrait { 12 | /// Registers a new request type `T` to the application. 13 | /// 14 | /// This method is used to register a new request type `T` to the application. The request type 15 | /// `T` must implement the `Deserialize` trait, and be `Send` and `Sync`. This is necessary for 16 | /// the request type to be safely shared across threads and for it to be deserialized from a 17 | /// HTTP response. 18 | /// 19 | /// # Type Parameters 20 | /// 21 | /// * `T`: The type of the request. This type must implement `Deserialize`, `Send`, and `Sync`. 22 | /// 23 | /// # Returns 24 | /// 25 | /// A mutable reference to the application. This is used to allow method chaining. 26 | /// 27 | /// # Examples 28 | /// 29 | /// ``` 30 | /// app.register_request_type::(); 31 | /// ``` 32 | fn register_request_type Deserialize<'a> + Send + Sync + 'static + Clone>( 33 | &mut self, 34 | ) -> &mut Self; 35 | } 36 | 37 | impl HttpTypedRequestTrait for App { 38 | fn register_request_type Deserialize<'a> + Send + Sync + 'static + Clone>( 39 | &mut self, 40 | ) -> &mut Self { 41 | self.add_event::>(); 42 | self.add_event::>(); 43 | self.add_event::>(); 44 | self.add_systems(PreUpdate, handle_typed_request::); 45 | self 46 | } 47 | } 48 | 49 | /// A struct that represents a typed HTTP request. 50 | /// 51 | /// This struct is used to represent a typed HTTP request. The type `T` is the type of the data that 52 | /// is expected to be returned by the HTTP request. The `Request` is the actual HTTP request that 53 | /// will be sent. 54 | /// 55 | /// # Type Parameters 56 | /// 57 | /// * `T`: The type of the data that is expected to be returned by the HTTP request. This type must 58 | /// implement `Deserialize`. 59 | /// 60 | /// # Fields 61 | /// 62 | /// * `request`: The actual HTTP request that will be sent. 63 | /// * `inner`: A marker field that uses `PhantomData` to express that it may hold data of type `T`. 64 | /// 65 | /// # Examples 66 | /// 67 | /// ``` 68 | /// let request = Request::new(); 69 | /// let typed_request = TypedRequest::new(request); 70 | /// ``` 71 | #[derive(Debug, Event)] 72 | pub struct TypedRequest 73 | where 74 | T: for<'a> Deserialize<'a>, 75 | { 76 | pub from_entity: Option, 77 | pub request: Request, 78 | inner: PhantomData, 79 | } 80 | 81 | impl serde::Deserialize<'a>> TypedRequest { 82 | pub fn new(request: Request, from_entity: Option) -> Self { 83 | TypedRequest { 84 | from_entity, 85 | request, 86 | inner: PhantomData, 87 | } 88 | } 89 | } 90 | 91 | /// A struct that represents a typed HTTP response. 92 | /// 93 | /// This struct is used to represent a typed HTTP response. The type `T` is the type of the data 94 | /// that is expected to be contained in the HTTP response. The `inner` field is the actual data 95 | /// contained in the HTTP response. 96 | /// 97 | /// # Type Parameters 98 | /// 99 | /// * `T`: The type of the data that is expected to be contained in the HTTP response. This type 100 | /// must implement `Deserialize`. 101 | /// 102 | /// # Fields 103 | /// 104 | /// * `inner`: The actual data contained in the HTTP response. 105 | /// 106 | /// # Examples 107 | /// 108 | /// ``` 109 | /// let response = TypedResponse { inner: MyResponseType }; 110 | /// ``` 111 | #[derive(Debug, Deref, Event)] 112 | pub struct TypedResponse 113 | where 114 | T: for<'a> Deserialize<'a>, 115 | { 116 | #[deref] 117 | inner: T, 118 | } 119 | 120 | impl serde::Deserialize<'a>> TypedResponse { 121 | /// Consumes the HTTP response and returns the inner data. 122 | pub fn into_inner(self) -> T { 123 | self.inner 124 | } 125 | 126 | /// Access inner value T from a TypedResponse reference 127 | pub fn inner(&self) -> &T { 128 | &self.inner 129 | } 130 | } 131 | 132 | #[derive(Event, Debug, Clone, Deref)] 133 | pub struct TypedResponseError { 134 | #[deref] 135 | pub err: String, 136 | pub response: Option, 137 | phantom: PhantomData, 138 | } 139 | 140 | impl TypedResponseError { 141 | pub fn new(err: String) -> Self { 142 | Self { 143 | err, 144 | response: None, 145 | phantom: Default::default(), 146 | } 147 | } 148 | 149 | pub fn response(mut self, response: Response) -> Self { 150 | self.response = Some(response); 151 | self 152 | } 153 | } 154 | 155 | /// A system that handles typed HTTP requests. 156 | fn handle_typed_request Deserialize<'a> + Send + Sync + Clone + 'static>( 157 | mut commands: Commands, 158 | mut req_res: ResMut, 159 | mut requests: EventReader>, 160 | q_tasks: Query<&RequestTask>, 161 | ) { 162 | let thread_pool = IoTaskPool::get(); 163 | for request in requests.read() { 164 | if req_res.is_available() { 165 | let (entity, has_from_entity) = if let Some(entity) = request.from_entity { 166 | (entity, true) 167 | } else { 168 | (commands.spawn_empty().id(), false) 169 | }; 170 | let req = request.request.clone(); 171 | let tx = get_channel(&mut commands, q_tasks, entity); 172 | thread_pool 173 | .spawn(async move { 174 | let mut command_queue = CommandQueue::default(); 175 | 176 | let response = ehttp::fetch_async(req).await; 177 | command_queue.push(move |world: &mut World| { 178 | match response { 179 | Ok(response) => { 180 | let result: Result = 181 | serde_json::from_slice(response.bytes.as_slice()); 182 | 183 | match result { 184 | // deserialize success, send response 185 | Ok(inner) => { 186 | world 187 | .get_resource_mut::>>() 188 | .unwrap() 189 | .send(TypedResponse { 190 | inner: inner.clone(), 191 | }); 192 | world.trigger_targets(TypedResponse { inner }, entity); 193 | } 194 | // deserialize error, send error + response 195 | Err(e) => { 196 | world 197 | .get_resource_mut::>>() 198 | .unwrap() 199 | .send( 200 | TypedResponseError::new(e.to_string()) 201 | .response(response.clone()), 202 | ); 203 | 204 | world.trigger_targets( 205 | TypedResponseError::::new(e.to_string()) 206 | .response(response), 207 | entity, 208 | ); 209 | } 210 | } 211 | } 212 | Err(e) => { 213 | world 214 | .get_resource_mut::>>() 215 | .unwrap() 216 | .send(TypedResponseError::new(e.to_string())); 217 | } 218 | } 219 | 220 | if !has_from_entity { 221 | world.entity_mut(entity).despawn(); 222 | } 223 | }); 224 | 225 | tx.send(command_queue).unwrap() 226 | }) 227 | .detach(); 228 | 229 | req_res.current_clients += 1; 230 | } 231 | } 232 | } 233 | --------------------------------------------------------------------------------