Compare commits

...

9 Commits

Author SHA1 Message Date
Valerio Ageno 74e2f4e873 fix ssr keyword 2024-07-08 09:24:20 +02:00
Valerio Ageno d9d62a91f7 Add keywords to crates 2024-07-08 09:19:00 +02:00
Valerio Ageno 77b34fbb7b feat: update version to v0.4.1 2024-07-07 12:24:45 +02:00
Valerio Ageno d3040aa63f feat: correct module visibility 2024-07-07 12:23:54 +02:00
Valerio Ageno 672e4b69d7 Proxy vite dev server (#10)
* refactor: pass reqwest from tuono_lib crate and prepared vite_reverse_proxy

* feat: add proxy entry point on vite side

* refactor: internal_handlers_folder

* feat: handle vite websocket tunnel

* feat: handle unexpect WebSocket messages

* feat: split dev/prod ssr handling

* feat: split js/rust bundle reloading

* feat: prevent close error on websocket connection

* feat: remove vite proxy on prod server

* feat: update version to v0.4.0
2024-07-07 11:44:36 +02:00
Valerio Ageno 9cd90ba62a Refactor server (#9)
* refactor: move catch_all in tuono_lib

* refactor: moved server to tuono_lib

* refactor: move router and server into tuono_lib

* refactor: reduce exports from examples

* refactor: re-organize exports

* refactor: removed mode set on project builder

* feat: update version to v0.3.1
2024-07-02 21:59:30 +02:00
Valerio Ageno b6d0bb13ef Handle redirections (#8)
* feat: support axum permanent redirect

* feat: lowercase route names

* feat: allow redirection on client side routing

* doc: update tutorial

* refactor: update useListenBrowserUrlUpdates hook

* refactor: moved initRouterStore to useRouterStore file

* feat: update version to v0.3.0

* fix: types
2024-06-29 11:58:04 +02:00
Valerio Ageno 7401a59346 update version to v0.2.5 2024-06-27 17:53:12 +02:00
Valerio Ageno 622ae93d68 fix: crates categories 2024-06-27 17:52:32 +02:00
31 changed files with 554 additions and 211 deletions
+3 -2
View File
@@ -1,13 +1,14 @@
[package]
name = "tuono"
version = "0.2.4"
version = "0.4.3"
edition = "2021"
authors = ["V. Ageno <valerioageno@yahoo.it>"]
description = "The react/rust fullstack framework"
keywords = [ "react", "typescript", "fullstack", "web", "ssr"]
repository = "https://github.com/Valerioageno/tuono"
readme = "../../README.md"
license-file = "../../LICENSE.md"
categories = ["web-programming", "reactjs", "typescript", "framework", "fullstack"]
categories = ["web-programming"]
include = [
"src/*.rs",
"Cargo.toml"
+7 -74
View File
@@ -47,13 +47,7 @@ pub const AXUM_ENTRY_POINT: &str = r##"
// File automatically generated
// Do not manually change it
use axum::extract::{Path, Request};
use axum::response::Html;
use axum::{routing::get, Router};
use tower_http::services::ServeDir;
use std::collections::HashMap;
use tuono_lib::{ssr, Ssr, Mode, GLOBAL_MODE, manifest::load_manifest};
use reqwest::Client;
use tuono_lib::{tokio, Mode, Server, axum::Router, axum::routing::get};
const MODE: Mode = /*MODE*/;
@@ -61,56 +55,16 @@ const MODE: Mode = /*MODE*/;
#[tokio::main]
async fn main() {
Ssr::create_platform();
let fetch = Client::new();
GLOBAL_MODE.set(MODE).unwrap();
if MODE == Mode::Prod {
load_manifest()
}
let app = Router::new()
let router = Router::new()
// ROUTE_BUILDER
.fallback_service(ServeDir::new("/*public_dir*/").fallback(get(catch_all)))
.with_state(fetch);
;
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
if MODE == Mode::Dev {
println!("\nDevelopment app ready at http://localhost:3000/");
} else {
println!("\nProduction app ready at http://localhost:3000/");
}
axum::serve(listener, app).await.unwrap();
}
async fn catch_all(Path(params): Path<HashMap<String, String>>, request: Request) -> Html<String> {
let pathname = &request.uri();
let headers = &request.headers();
let req = tuono_lib::Request::new(pathname, headers, params);
// TODO: remove unwrap
let payload = tuono_lib::Payload::new(&req, &"")
.client_payload()
.unwrap();
let result = ssr::Js::SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload)));
match result {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string()),
}
Server::init(router, MODE).start().await
}
"##;
const ROOT_FOLDER: &str = "src/routes";
const DEV_FOLDER: &str = ".tuono";
const DEV_PUBLIC_DIR: &str = "public";
const PROD_PUBLIC_DIR: &str = "out/client";
#[derive(Debug, PartialEq, Eq)]
struct Route {
@@ -153,7 +107,7 @@ impl Route {
}
Route {
module_import: module.as_str().to_string().replace('/', "_"),
module_import: module.as_str().to_string().replace('/', "_").to_lowercase(),
axum_route,
}
}
@@ -254,12 +208,6 @@ pub fn bundle_axum_source(mode: Mode) -> io::Result<()> {
}
fn generate_axum_source(source_builder: &SourceBuilder, mode: Mode) -> String {
let public_dir = if mode == Mode::Prod {
PROD_PUBLIC_DIR
} else {
DEV_PUBLIC_DIR
};
AXUM_ENTRY_POINT
.replace(
"// ROUTE_BUILDER\n",
@@ -269,7 +217,6 @@ fn generate_axum_source(source_builder: &SourceBuilder, mode: Mode) -> String {
"// MODULE_IMPORTS\n",
&create_modules_declaration(&source_builder.route_map),
)
.replace("/*public_dir*/", public_dir)
.replace("/*MODE*/", mode.as_str())
}
@@ -329,6 +276,7 @@ mod tests {
"/home/user/Documents/tuono/src/routes/index.rs",
"/home/user/Documents/tuono/src/routes/posts/index.rs",
"/home/user/Documents/tuono/src/routes/posts/[post].rs",
"/home/user/Documents/tuono/src/routes/posts/UPPERCASE.rs",
];
routes
@@ -340,6 +288,7 @@ mod tests {
("/about.rs", "about"),
("/posts/index.rs", "posts_index"),
("/posts/[post].rs", "posts_dyn_post"),
("/posts/UPPERCASE.rs", "posts_uppercase"),
];
results.into_iter().for_each(|(path, module_import)| {
@@ -410,20 +359,4 @@ mod tests {
assert_eq!(dev, "Mode::Dev");
assert_eq!(prod, "Mode::Prod");
}
#[test]
fn should_replace_the_correct_public_folder_dev() {
let source_builder = SourceBuilder::new();
let source = generate_axum_source(&source_builder, Mode::Dev);
assert!(source.contains(r#"ServeDir::new("public")"#))
}
#[test]
fn should_replace_the_correct_public_folder_prod() {
let source_builder = SourceBuilder::new();
let source = generate_axum_source(&source_builder, Mode::Prod);
assert!(source.contains(r#"ServeDir::new("out/client")"#))
}
}
+15 -10
View File
@@ -57,27 +57,32 @@ pub async fn watch() -> Result<()> {
build_ssr_bundle.to_wait().await;
let wx = Watchexec::new(move |mut action| {
let mut should_reload = false;
let mut should_reload_ssr_bundle = false;
let mut should_reload_rust_server = false;
for event in action.events.iter() {
for path in event.paths() {
if path.0.to_string_lossy().ends_with(".rs")
// Either tsx and jsx
|| path.0.to_string_lossy().ends_with("sx")
{
should_reload = true
if path.0.to_string_lossy().ends_with(".rs") {
should_reload_rust_server = true
}
// Either tsx and jsx
if path.0.to_string_lossy().ends_with("sx") {
should_reload_ssr_bundle = true
}
}
}
if should_reload {
if should_reload_rust_server {
println!("Reloading...");
run_server.stop();
build_ssr_bundle.stop();
build_ssr_bundle.start();
bundle_axum_source(Mode::Dev).expect("Failed to bunlde rust source");
run_server.start();
println!("Ready!");
}
if should_reload_ssr_bundle {
build_ssr_bundle.stop();
build_ssr_bundle.start();
}
// if Ctrl-C is received, quit
+14 -6
View File
@@ -1,13 +1,14 @@
[package]
name = "tuono_lib"
version = "0.2.4"
version = "0.4.3"
edition = "2021"
authors = ["V. Ageno <valerioageno@yahoo.it>"]
description = "The react/rust fullstack framework"
keywords = [ "react", "typescript", "fullstack", "web", "ssr"]
repository = "https://github.com/Valerioageno/tuono"
readme = "../../README.md"
license-file = "../../LICENSE.md"
categories = ["web-programming", "reactjs", "typescript", "framework", "fullstack"]
categories = ["web-programming"]
include = [
"src/*.rs",
"Cargo.toml"
@@ -19,13 +20,20 @@ path = "src/lib.rs"
[dependencies]
ssr_rs = "0.5.5"
axum = "0.7.5"
axum = {version = "0.7.5", features = ["json", "ws"]}
tokio = { version = "1.37.0", features = ["full"] }
serde = { version = "1.0.202", features = ["derive"] }
erased-serde = "0.4.5"
serde_json = "1.0"
tuono_lib_macros = {path = "../tuono_lib_macros", version = "0.2.4"}
reqwest = {version = "0.12.4", features = ["json", "stream"]}
once_cell = "1.19.0"
lazy_static = "1.5.0"
regex = "1.10.5"
either = "1.13.0"
tower-http = {version = "0.5.2", features = ["fs"]}
tuono_lib_macros = {path = "../tuono_lib_macros", version = "0.4.3"}
# Match the same version used by axum
tokio-tungstenite = "0.21.0"
futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }
tungstenite = "0.23.0"
+24
View File
@@ -0,0 +1,24 @@
use crate::{ssr::Js, Payload};
use axum::extract::{Path, Request};
use axum::response::Html;
use std::collections::HashMap;
pub async fn catch_all(
Path(params): Path<HashMap<String, String>>,
request: Request,
) -> Html<String> {
let pathname = &request.uri();
let headers = &request.headers();
let req = crate::Request::new(pathname, headers, params);
// TODO: remove unwrap
let payload = Payload::new(&req, &"").client_payload().unwrap();
let result = Js::render_to_string(Some(&payload));
match result {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string()),
}
}
+13 -5
View File
@@ -1,14 +1,22 @@
pub mod manifest;
mod catch_all;
mod manifest;
mod mode;
mod payload;
mod request;
mod response;
mod server;
mod ssr;
mod vite_reverse_proxy;
mod vite_websocket_proxy;
pub mod ssr;
pub use mode::{Mode, GLOBAL_MODE};
pub use mode::Mode;
pub use payload::Payload;
pub use request::Request;
pub use response::{Props, Response};
pub use ssr_rs::Ssr;
pub use server::Server;
pub use tuono_lib_macros::handler;
// Re-exports
pub use axum;
pub use reqwest;
pub use tokio;
+2 -1
View File
@@ -1,4 +1,5 @@
use crate::{manifest::MANIFEST, Mode, GLOBAL_MODE};
use crate::manifest::MANIFEST;
use crate::mode::{Mode, GLOBAL_MODE};
use erased_serde::Serialize;
use regex::Regex;
use serde::Serialize as SerdeSerialize;
+51 -9
View File
@@ -1,7 +1,7 @@
use crate::Request;
use crate::{ssr::Js, Payload};
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse};
use axum::response::{Html, IntoResponse, Redirect, Response as AxumResponse};
use axum::Json;
use erased_serde::Serialize;
@@ -15,6 +15,41 @@ pub enum Response {
Props(Props),
}
#[derive(serde::Serialize)]
struct JsonResponseInfo {
redirect_destination: Option<String>,
}
impl JsonResponseInfo {
fn new(redirect_destination: Option<String>) -> JsonResponseInfo {
JsonResponseInfo {
redirect_destination,
}
}
}
#[derive(serde::Serialize)]
struct JsonResponse<'a> {
data: Option<&'a dyn Serialize>,
info: JsonResponseInfo,
}
impl<'a> JsonResponse<'a> {
fn new(props: &'a dyn Serialize) -> Self {
JsonResponse {
data: Some(props),
info: JsonResponseInfo::new(None),
}
}
fn new_redirect(destination: String) -> Self {
JsonResponse {
data: None,
info: JsonResponseInfo::new(Some(destination)),
}
}
}
impl Props {
pub fn new(data: impl Serialize + 'static) -> Self {
Props {
@@ -32,25 +67,32 @@ impl Props {
}
impl Response {
pub fn render_to_string(&self, req: Request) -> impl IntoResponse {
pub fn render_to_string(&self, req: Request) -> AxumResponse {
match self {
Self::Props(Props { data, http_code }) => {
let payload = Payload::new(&req, data).client_payload().unwrap();
match Js::SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload))) {
Ok(html) => (*http_code, Html(html)),
Err(_) => (*http_code, Html("500 Internal server error".to_string())),
match Js::render_to_string(Some(&payload)) {
Ok(html) => (*http_code, Html(html)).into_response(),
Err(_) => {
(*http_code, Html("500 Internal server error".to_string())).into_response()
}
}
}
// TODO: Handle here other enum arms
_ => todo!(),
Self::Redirect(to) => Redirect::permanent(to).into_response(),
}
}
pub fn json(&self) -> impl IntoResponse {
match self {
Self::Props(Props { data, http_code }) => (*http_code, Json(data)).into_response(),
_ => (StatusCode::INTERNAL_SERVER_ERROR, axum::Json("{}")).into_response(),
Self::Props(Props { data, http_code }) => {
(*http_code, Json(JsonResponse::new(data))).into_response()
}
Self::Redirect(destination) => (
StatusCode::PERMANENT_REDIRECT,
Json(JsonResponse::new_redirect(destination.to_string())),
)
.into_response(),
}
}
}
+65
View File
@@ -0,0 +1,65 @@
use crate::mode::{Mode, GLOBAL_MODE};
use crate::manifest::load_manifest;
use axum::routing::{get, Router};
use ssr_rs::Ssr;
use tower_http::services::ServeDir;
use crate::{
catch_all::catch_all, vite_reverse_proxy::vite_reverse_proxy,
vite_websocket_proxy::vite_websocket_proxy,
};
const DEV_PUBLIC_DIR: &str = "public";
const PROD_PUBLIC_DIR: &str = "out/client";
pub struct Server {
router: Router<reqwest::Client>,
mode: Mode,
}
impl Server {
pub fn init(router: Router<reqwest::Client>, mode: Mode) -> Server {
Ssr::create_platform();
GLOBAL_MODE.set(mode).unwrap();
if mode == Mode::Prod {
load_manifest()
}
Server { router, mode }
}
pub async fn start(&self) {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
let fetch = reqwest::Client::new();
if self.mode == Mode::Dev {
println!("\nDevelopment app ready at http://localhost:3000/");
let router = self
.router
.to_owned()
.route("/vite-server/", get(vite_websocket_proxy))
.route("/vite-server/*path", get(vite_reverse_proxy))
.fallback_service(ServeDir::new(DEV_PUBLIC_DIR).fallback(get(catch_all)))
.with_state(fetch);
axum::serve(listener, router)
.await
.expect("Failed to serve development server");
} else {
println!("\nProduction app ready at http://localhost:3000/");
let router = self
.router
.to_owned()
.fallback_service(ServeDir::new(PROD_PUBLIC_DIR).fallback(get(catch_all)))
.with_state(fetch);
axum::serve(listener, router)
.await
.expect("Failed to serve production server");
}
}
}
+33 -12
View File
@@ -1,27 +1,48 @@
use crate::{Mode, GLOBAL_MODE};
use lazy_static::lazy_static;
use crate::mode::{Mode, GLOBAL_MODE};
use ssr_rs::Ssr;
use std::cell::RefCell;
use std::fs::read_to_string;
use std::path::PathBuf;
lazy_static! {
static ref BUNDLE_PATH: &'static str = {
if GLOBAL_MODE.get().unwrap() == &Mode::Dev {
return "./.tuono/server/dev-server.js";
}
"./out/server/prod-server.js"
};
}
/// For the server side rendering we need to split the implementation between dev and prod.
/// This completely remove the multi-thread optimization on dev but allow the dev server to
/// update the SSR result without reloading the whole server.
pub struct Js;
impl Js {
pub fn render_to_string(payload: Option<&str>) -> Result<String, &'static str> {
let mode = GLOBAL_MODE.get().expect("Failed to get GLOBAL_MODE");
if *mode == Mode::Dev {
DevJs::render_to_string(payload)
} else {
ProdJs::SSR.with(|ssr| ssr.borrow_mut().render_to_string(payload))
}
}
}
struct ProdJs;
impl ProdJs {
thread_local! {
pub static SSR: RefCell<Ssr<'static, 'static>> = RefCell::new(
Ssr::from(
read_to_string(PathBuf::from(*BUNDLE_PATH)).expect("Server bundle not found"), ""
read_to_string(PathBuf::from("./out/server/prod-server.js")).expect("Server bundle not found"), ""
).unwrap()
)
}
}
struct DevJs;
impl DevJs {
pub fn render_to_string(params: Option<&str>) -> Result<String, &'static str> {
Ssr::from(
read_to_string(PathBuf::from("./.tuono/server/dev-server.js"))
.expect("Server bundle not found"),
"",
)
.unwrap()
.render_to_string(params)
}
}
@@ -0,0 +1,33 @@
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::{HeaderName, HeaderValue};
use axum::response::{IntoResponse, Response};
use reqwest::Client;
const VITE_URL: &str = "http://localhost:3001/vite-server";
pub async fn vite_reverse_proxy(
State(client): State<Client>,
Path(path): Path<String>,
) -> impl IntoResponse {
match client.get(format!("{VITE_URL}/{path}")).send().await {
Ok(res) => {
let mut response_builder = Response::builder().status(res.status().as_u16());
{
let headers = response_builder.headers_mut().unwrap();
res.headers().into_iter().for_each(|(name, value)| {
let name = HeaderName::from_bytes(name.as_ref()).unwrap();
let value = HeaderValue::from_bytes(value.as_ref()).unwrap();
headers.insert(name, value);
});
}
response_builder
.body(Body::from_stream(res.bytes_stream()))
.unwrap()
}
Err(_) => todo!(),
}
}
@@ -0,0 +1,104 @@
use axum::extract::ws::{self, WebSocket, WebSocketUpgrade};
use axum::response::IntoResponse;
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::{Error, Message};
use tungstenite::client::IntoClientRequest;
use tungstenite::ClientRequestBuilder;
const VITE_WS: &str = "ws://localhost:3001/vite-server/";
const VITE_WS_PROTOCOL: &str = "vite-hmr";
/// This is the entry point to proxy the vite's WebSocket.
/// The proxy is needed for allowing all the development requests to point
/// to localhost:3000/*. This enabled the framework to be developed in a Docker
/// environment with just the 3000 port exposed.
pub async fn vite_websocket_proxy(ws: WebSocketUpgrade) -> impl IntoResponse {
ws.protocols([VITE_WS_PROTOCOL]).on_upgrade(handle_socket)
}
async fn handle_socket(mut tuono_socket: WebSocket) {
// Send back a message to confirm connection
if tuono_socket
.send(ws::Message::Ping("tuono connected".into()))
.await
.is_err()
{
// If is error close the connection
return;
}
let vite_ws_request = ClientRequestBuilder::new(VITE_WS.parse().unwrap())
.with_sub_protocol(VITE_WS_PROTOCOL)
.into_client_request()
.expect("Failed to create vite WS request");
let vite_socket = match connect_async(vite_ws_request).await {
Ok((stream, _)) => {
// Connected to vite's WebSocket
stream
}
Err(e) => {
eprintln!("Failed to connect to vite's WebSocket. Error: {e}");
// As fallback vite automatically connect to port 3001.
return;
}
};
let (mut vite_sender, mut vite_receiver) = vite_socket.split();
let (mut tuono_sender, mut tuono_receiver) = tuono_socket.split();
// Handle browser messages.
// Every message gets forwarded to the vite WebSocket
tokio::spawn(async move {
while let Some(msg) = tuono_receiver.next().await {
if let Ok(msg) = msg {
let msg_to_vite = match msg.clone() {
ws::Message::Text(str) => Message::Text(str),
ws::Message::Pong(payload) => Message::Pong(payload),
ws::Message::Ping(payload) => Message::Ping(payload),
ws::Message::Binary(payload) => Message::Binary(payload),
// Hard to match axum and tungstenite close payload.
// Not a priority
ws::Message::Close(_) => Message::Close(None),
};
vite_sender
.send(msg_to_vite)
.await
.expect("Failed to tunnel msg to vite's WebSocket");
msg
} else {
// Close browser's WebSocket connection.
return;
};
}
});
// Handle vite messages.
// Every message gets forwarded to the browser.
tokio::spawn(async move {
while let Some(Ok(msg)) = vite_receiver.next().await {
let msg_to_browser = match msg {
Message::Text(str) => ws::Message::Text(str),
Message::Ping(payload) => ws::Message::Ping(payload),
Message::Pong(payload) => ws::Message::Pong(payload),
Message::Binary(payload) => ws::Message::Binary(payload),
// Hard to match axum and tungstenite close payload.
// Not a priority
Message::Close(_) => ws::Message::Close(None),
_ => {
eprintln!("Unexpected message from the vite WebSocket to the browser: {msg:?}");
ws::Message::Text("Unhandled".to_string())
}
};
if let Err(err) = tuono_sender.send(msg_to_browser).await {
if err.to_string() != Error::AlreadyClosed.to_string() {
eprintln!("Failed to send back message from vite to browser: {err}")
}
}
}
});
}
+3 -2
View File
@@ -1,12 +1,13 @@
[package]
name = "tuono_lib_macros"
version = "0.2.4"
version = "0.4.3"
edition = "2021"
description = "The react/rust fullstack framework"
keywords = [ "react", "typescript", "fullstack", "web", "ssr"]
repository = "https://github.com/Valerioageno/tuono"
readme = "../../README.md"
license-file = "../../LICENSE.md"
categories = ["web-programming", "reactjs", "typescript", "framework", "fullstack"]
categories = ["web-programming"]
include = [
"src/*.rs",
"Cargo.toml"
+6 -7
View File
@@ -8,17 +8,16 @@ pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
let fn_name = item.clone().sig.ident;
quote! {
use axum::response::IntoResponse;
use tuono_lib::axum::response::IntoResponse;
use std::collections::HashMap;
use axum::extract::{State, Path};
use reqwest::Client;
use tuono_lib::axum::extract::{State, Path};
#item
pub async fn route(
Path(params): Path<HashMap<String, String>>,
State(client): State<Client>,
request: axum::extract::Request
State(client): State<tuono_lib::reqwest::Client>,
request: tuono_lib::axum::extract::Request
) -> impl IntoResponse {
let pathname = &request.uri();
let headers = &request.headers();
@@ -30,8 +29,8 @@ pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
pub async fn api(
Path(params): Path<HashMap<String, String>>,
State(client): State<Client>,
request: axum::extract::Request
State(client): State<tuono_lib::reqwest::Client>,
request: tuono_lib::axum::extract::Request
) -> impl IntoResponse{
let pathname = &request.uri();
let headers = &request.headers();
+37 -1
View File
@@ -23,6 +23,7 @@ Typescript and Rust knowledge is not a requirement though!
* [Create a stand-alone component](#create-a-stand-alone-component)
* [Create the /pokemons/[pokemon] route](#create-the-pokemonspokemon-route)
* [Error handling](#error-handling)
* [Handle redirections](#handle-redirections)
* [Building for production](#building-for-production)
* [Conclusion](#conclusion)
@@ -98,7 +99,7 @@ The file `index.rs` represents the server side capabilities for the index route.
- Passing server side props
- Changing http status code
- Redirect/Rewrite to a different route (Available soon)
- Redirecting to a different route
## Tutorial introduction
@@ -542,6 +543,41 @@ async fn get_all_pokemons(_req: Request<'_>, fetch: reqwest::Client) -> Response
If you now try to load a not existing pokemon (`http://localhost:3000/pokemons/tuono-pokemon`) you will
correctly receive a 404 status code in the console.
## Handle redirections
What if there is a pokemon among all of them that should be considered the GOAT? What
we are going to do right now is creating a new route `/pokemons/GOAT` that points to the best
pokemon of the first generation.
First let's create a new route by just creating an new file `/pokemons/GOAT.rs` and pasting the following code:
```rs
// src/routes/pokemons/GOAT.rs
use tuono_lib::{Request, Response};
#[tuono_lib::handler]
async fn redirect_to_goat(_: Request<'_>, _: reqwest::Client) -> Response {
// Of course the GOAT is mewtwo - feel free to select your favourite 😉
Response::Redirect("/pokemons/mewtwo".to_string())
}
```
Now let's create the button in the home page to actually point to it!
```diff
// src/routes/index.tsx
<ul style={{ flexWrap: 'wrap', display: 'flex', gap: 10 }}>
++ <PokemonLink pokemon={{ name: 'GOAT' }} id={0} />
{data.results.map((pokemon, i) => {
return <PokemonLink pokemon={pokemon} id={i + 1} key={i} />
})}
</ul>
```
Now at [http://localhost:3000/](http:/localhost:3000/) you will find a new link at the beginning of the list.
Click on it and see the application automatically redirecting you to your favourite pokemon's route!
## Building for production
The source now is ready to be released. Both server and client have been managed in a unoptimized way
-6
View File
@@ -8,11 +8,5 @@ name = "tuono"
path = ".tuono/main.rs"
[dependencies]
axum = {version = "0.7.5", features = ["json"]}
tokio = { version = "1.37.0", features = ["full"] }
tower-http = {version = "0.5.2", features = ["fs"]}
serde = { version = "1.0.202", features = ["derive"] }
tuono_lib = { path = "../../crates/tuono_lib/"}
serde_json = "1.0"
reqwest = {version = "0.12.4", features = ["json"]}
+1 -6
View File
@@ -8,11 +8,6 @@ name = "tuono"
path = ".tuono/main.rs"
[dependencies]
axum = {version = "0.7.5", features = ["json"]}
tokio = { version = "1.37.0", features = ["full"] }
tower-http = {version = "0.5.2", features = ["fs"]}
serde = { version = "1.0.202", features = ["derive"] }
tuono_lib = { path = "../../crates/tuono_lib/"}
serde_json = "1.0"
reqwest = {version = "0.12.4", features = ["json"]}
serde = { version = "1.0.202", features = ["derive"] }
+4 -4
View File
@@ -1,6 +1,6 @@
// src/routes/index.rs
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use tuono_lib::reqwest::{Client, StatusCode};
use tuono_lib::{Props, Request, Response};
const ALL_POKEMON: &str = "https://pokeapi.co/api/v2/pokemon?limit=151";
@@ -17,8 +17,8 @@ struct Pokemon {
}
#[tuono_lib::handler]
async fn get_all_pokemons(_req: Request<'_>, fetch: reqwest::Client) -> Response {
return match fetch.get(ALL_POKEMON).send().await {
async fn get_all_pokemons(_req: Request<'_>, fetch: Client) -> Response {
match fetch.get(ALL_POKEMON).send().await {
Ok(res) => {
let data = res.json::<Pokemons>().await.unwrap();
Response::Props(Props::new(data))
@@ -27,5 +27,5 @@ async fn get_all_pokemons(_req: Request<'_>, fetch: reqwest::Client) -> Response
"{}", // Return empty JSON
StatusCode::INTERNAL_SERVER_ERROR,
)),
};
}
}
+1
View File
@@ -37,6 +37,7 @@ export default function IndexPage({
</div>
</div>
<ul style={{ flexWrap: 'wrap', display: 'flex', gap: 10 }}>
<PokemonLink pokemon={{ name: 'GOAT' }} id={0} />
{data.results.map((pokemon, i) => {
return <PokemonLink pokemon={pokemon} id={i + 1} key={i} />
})}
@@ -0,0 +1,7 @@
// src/routes/pokemons/GOAT.rs
use tuono_lib::{reqwest::Client, Request, Response};
#[tuono_lib::handler]
async fn redirect_to_goat(_: Request<'_>, _: Client) -> Response {
Response::Redirect("/pokemons/mewtwo".to_string())
}
@@ -1,6 +1,6 @@
// src/routes/pokemons/[pokemon].rs
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use tuono_lib::reqwest::{Client, StatusCode};
use tuono_lib::{Props, Request, Response};
const POKEMON_API: &str = "https://pokeapi.co/api/v2/pokemon";
@@ -14,11 +14,11 @@ struct Pokemon {
}
#[tuono_lib::handler]
async fn get_pokemon(req: Request<'_>, fetch: reqwest::Client) -> Response {
async fn get_pokemon(req: Request<'_>, fetch: Client) -> Response {
// The param `pokemon` is defined in the route filename [pokemon].rs
let pokemon = req.params.get("pokemon").unwrap();
return match fetch.get(format!("{POKEMON_API}/{pokemon}")).send().await {
match fetch.get(format!("{POKEMON_API}/{pokemon}")).send().await {
Ok(res) => {
if res.status() == StatusCode::NOT_FOUND {
return Response::Props(Props::new_with_status("{}", StatusCode::NOT_FOUND));
@@ -30,5 +30,5 @@ async fn get_pokemon(req: Request<'_>, fetch: reqwest::Client) -> Response {
"{}",
StatusCode::INTERNAL_SERVER_ERROR,
)),
};
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "tuono-lazy-fn-vite-plugin",
"version": "0.2.4",
"version": "0.4.3",
"description": "Plugin for the tuono's lazy fn. Tuono is the react/rust fullstack framework",
"scripts": {
"dev": "vite build --watch",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "tuono",
"version": "0.2.4",
"version": "0.4.3",
"description": "The react/rust fullstack framework",
"scripts": {
"dev": "vite build --watch",
+5 -1
View File
@@ -12,6 +12,8 @@ const BASE_CONFIG: InlineConfig = {
plugins: [react(), ViteFsRouter(), LazyLoadingPlugin()],
}
const VITE_PORT = 3001
export function developmentSSRBundle() {
;(async () => {
await build({
@@ -43,8 +45,10 @@ export function developmentCSRWatch() {
;(async () => {
const server = await createServer({
...BASE_CONFIG,
// Entry point for the development vite proxy
base: '/vite-server/',
server: {
port: 3001,
port: VITE_PORT,
strictPort: true,
},
build: {
@@ -1,7 +1,9 @@
import { getRouterContext } from './RouterContext'
import { Matches } from './Matches'
import { useRouterStore } from '../hooks/useRouterStore'
import React, { useEffect, useLayoutEffect, type ReactNode } from 'react'
import { useListenBrowserUrlUpdates } from '../hooks/useListenBrowserUrlUpdates'
import React, { type ReactNode } from 'react'
import { initRouterStore } from '../hooks/useRouterStore'
import type { ServerProps } from '../types'
type Router = any
@@ -15,11 +17,6 @@ interface RouterProviderProps {
serverProps?: ServerProps
}
interface ServerProps {
router: Location
props: any
}
function RouterContextProvider({
router,
children,
@@ -47,58 +44,13 @@ function RouterContextProvider({
)
}
const initRouterStore = (props?: ServerProps): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
if (typeof window === 'undefined') {
updateLocation({
pathname: props?.router.pathname || '',
hash: '',
href: '',
searchStr: '',
})
}
useLayoutEffect(() => {
const { pathname, hash, href, search } = window.location
updateLocation({
pathname,
hash,
href,
searchStr: search,
search: new URLSearchParams(search),
})
}, [])
}
const useListenUrlUpdates = (): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
const updateLocationOnPopStateChange = ({ target }: any): void => {
const { pathname, hash, href, search } = target.location
updateLocation({
pathname,
hash,
href,
searchStr: search,
search: new URLSearchParams(search),
})
}
useEffect(() => {
window.addEventListener('popstate', updateLocationOnPopStateChange)
return (): void => {
window.removeEventListener('popstate', updateLocationOnPopStateChange)
}
}, [])
}
export function RouterProvider({
router,
serverProps,
}: RouterProviderProps): JSX.Element {
initRouterStore(serverProps)
useListenUrlUpdates()
useListenBrowserUrlUpdates()
return (
<RouterContextProvider router={router}>
@@ -0,0 +1,27 @@
import { useRouterStore } from './useRouterStore'
import { useEffect } from 'react'
/*
* This hook is meant to handle just browser related location updates
* like the back and forward buttons.
*/
export const useListenBrowserUrlUpdates = (): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
const updateLocationOnPopStateChange = ({ target }: any): void => {
const { pathname, hash, href, search } = target.location
updateLocation({
pathname,
hash,
href,
searchStr: search,
search: new URLSearchParams(search),
})
}
useEffect(() => {
window.addEventListener('popstate', updateLocationOnPopStateChange)
return (): void => {
window.removeEventListener('popstate', updateLocationOnPopStateChange)
}
}, [])
}
@@ -1,4 +1,7 @@
import { create } from 'zustand'
import { useLayoutEffect } from 'react'
import type { ServerProps } from '../types'
export interface ParsedLocation {
href: string
@@ -20,6 +23,30 @@ interface RouterState {
updateLocation: (loc: ParsedLocation) => void
}
export const initRouterStore = (props?: ServerProps): void => {
const updateLocation = useRouterStore((st) => st.updateLocation)
if (typeof window === 'undefined') {
updateLocation({
pathname: props?.router.pathname || '',
hash: '',
href: '',
searchStr: '',
})
}
useLayoutEffect(() => {
const { pathname, hash, href, search } = window.location
updateLocation({
pathname,
hash,
href,
searchStr: search,
search: new URLSearchParams(search),
})
}, [])
}
export const useRouterStore = create<RouterState>()((set) => ({
isLoading: false,
isTransitioning: false,
@@ -1,6 +1,7 @@
import { useState, useEffect, useRef } from 'react'
import type { Route } from '../route'
import { useRouterStore } from './useRouterStore'
import { fromUrlToParsedLocation } from '../utils/from-url-to-parsed-location'
const isServer = typeof document === 'undefined'
@@ -15,6 +16,19 @@ declare global {
}
}
interface TuonoApi {
data?: any
info: {
redirect_destination?: string
}
}
const fetchClientSideData = async (): Promise<TuonoApi> => {
const res = await fetch(`/__tuono/data${location.pathname}`)
const data: TuonoApi = await res.json()
return data
}
/*
* Use the props provided by the SSR and dehydrate the
* props for client side usage.
@@ -27,7 +41,10 @@ export function useServerSideProps<T>(
serverSideProps: T,
): UseServerSidePropsReturn {
const isFirstRendering = useRef<boolean>(true)
const location = useRouterStore((st) => st.location)
const [location, updateLocation] = useRouterStore((st) => [
st.location,
st.updateLocation,
])
const [isLoading, setIsLoading] = useState<boolean>(
// Force loading if has handler
route.options.hasHandler &&
@@ -53,8 +70,22 @@ export function useServerSideProps<T>(
;(async (): Promise<void> => {
setIsLoading(true)
try {
const res = await fetch(`/__tuono/data${location.pathname}`)
setData(await res.json())
const response = await fetchClientSideData()
if (response.info.redirect_destination) {
const parsedLocation = fromUrlToParsedLocation(
response.info.redirect_destination,
)
history.pushState(
parsedLocation.pathname,
'',
parsedLocation.pathname,
)
updateLocation(parsedLocation)
return
}
setData(response.data)
} catch (error) {
throw Error('Failed loading Server Side Data', { cause: error })
} finally {
+5
View File
@@ -2,3 +2,8 @@ export interface Segment {
type: 'pathname' | 'param' | 'wildcard'
value: string
}
export interface ServerProps {
router: Location
props: any
}
@@ -0,0 +1,16 @@
import type { ParsedLocation } from '../hooks/useRouterStore'
// TODO: improve the whole react/rust URL parsing logic
export function fromUrlToParsedLocation(href: string): ParsedLocation {
/*
* This function works on both server and client.
* For this reason we can't rely on the browser's URL api
*/
return {
href,
pathname: href,
search: undefined,
searchStr: '',
hash: '',
}
}
+6 -3
View File
@@ -7,15 +7,18 @@ import { createRouter } from '../router'
type RouteTree = any
type Mode = 'Dev' | 'Prod'
const TUONO_DEV_SERVER_PORT = 3000
const VITE_PROXY_PATH = '/vite-server'
const VITE_DEV_AND_HMR = `<script type="module">
import RefreshRuntime from 'http://localhost:3001/@react-refresh'
import RefreshRuntime from 'http://localhost:${TUONO_DEV_SERVER_PORT}${VITE_PROXY_PATH}/@react-refresh'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
<script type="module" src="http://localhost:3001/@vite/client"></script>
<script type="module" src="http://localhost:3001/client-main.tsx"></script>`
<script type="module" src="http://localhost:${TUONO_DEV_SERVER_PORT}${VITE_PROXY_PATH}/@vite/client"></script>
<script type="module" src="http://localhost:${TUONO_DEV_SERVER_PORT}${VITE_PROXY_PATH}/client-main.tsx"></script>`
function generateCssLinks(cssBundles: string[], mode: Mode): string {
if (mode === 'Dev') return ''