yew_server_hook
A procedural macro that generates both server-side API handlers and client-side Yew hooks from a single function definition. Write your backend logic once, and automatically get both the Axum server endpoint and the Yew hook to call it.
Features
- Single Source of Truth: Define your API logic once, use it everywhere
- Type Safety: Full type checking between client and server
- Automatic Serialization: Handles JSON serialization/deserialization automatically
- Multiple HTTP Methods: Support for GET, POST, PUT, DELETE, and PATCH
- Smart Parameter Handling: Query parameters for GET, JSON body for other methods
- Loading States: Built-in loading and updating state management
- Error Handling: Automatic error propagation and parsing
- SSR Support: Server-side rendering compatible with feature flags
- Auto Route Registration: Routes are automatically registered using the inventory crate
Installation
Add this to your Cargo.toml:
[]
= "0.1"
= { = "0.8", = ["json", "macros"] }
= { = "1.0", = ["derive"] }
= "1.0"
= "0.21"
= "0.5"
= "0.4"
Quick Start
Basic Example
use yewserverhook;
pub async
This generates:
- A server handler at
/api/hello(GET) - A Yew hook
use_get_hello() - A direct callable function
get_hello()for programmatic use
Using the Hook in a Component
use *;
Example with Parameters
pub async
Use in a component:
POST Request Example
pub async
// Direct call (not using the hook):
async
HTTP Methods
The macro supports all standard HTTP methods:
GET- Parameters sent as query stringsPOST- Parameters sent as JSON body (default)PUT- Parameters sent as JSON bodyDELETE- Parameters sent as JSON bodyPATCH- Parameters sent as JSON body
API Hook State
The generated hook returns an ApiHook<T> struct with:
The DataState<T> enum:
Features
SSR Feature Flag
The crate supports server-side rendering through the ssr feature flag:
[]
= []
- When
ssris enabled: Server handlers are generated - When
ssris disabled: Client-side hooks and fetch functions are generated
Route Registration
Routes are automatically registered using the inventory crate. To use the auto-registered routes:
use Router;
// Routes are automatically collected and can be registered
let app = new
.merge;
Requirements
Your function must:
- Be
async - Return a
Result<T, E>where bothTandEimplementSerializeandDeserialize - Have parameters that implement
Serialize,Deserialize, andClone
Generated Code
For each annotated function, the macro generates:
-
Parameter Struct (if function has parameters):
-
Server Handler (with
ssrfeature):pub async -
Client Hook:
-
Direct Client Function:
pub async
Testing
Run tests with:
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.