Compare commits

...

14 Commits

Author SHA1 Message Date
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
Valerio Ageno b4207feb7e Update version to v0.2.4 2024-06-27 17:47:09 +02:00
Valerio Ageno 332fdb70ca Update ssr_rs to v0.5.5 2024-06-27 17:46:19 +02:00
Valerio Ageno b9abfb64c0 feat: update version to v0.2.3 2024-06-25 18:53:17 +02:00
Valerio Ageno 3ca8861d85 feat: use the correct public folder according to the mode 2024-06-25 18:48:55 +02:00
Valerio Ageno 0c93aab13f Update tutorial.md 2024-06-25 14:26:27 +02:00
Valerio Ageno 208b49cfc8 Update tutorial.md 2024-06-25 14:26:01 +02:00
Valerio Ageno db0a2d9d1d Update README.md 2024-06-25 14:24:59 +02:00
Valerio Ageno c123e93433 Update scaffold_project.rs 2024-06-25 14:23:22 +02:00
Valerio Ageno 35557d296d feat: update version to v0.2.2 2024-06-25 08:35:09 +02:00
Gábor Szabó d0d6550d7e It is better to use the repository field in Cargo.toml (#7) 2024-06-25 07:42:04 +02:00
26 changed files with 333 additions and 153 deletions
+3 -1
View File
@@ -74,7 +74,9 @@ Now to execute it just run `cargo run --release`.
- rust
- cargo
- node
- pnpm (other package managers support will be added soon)
- npm/pnpm/yarn*
> yarn [pnp](https://yarnpkg.com/features/pnp) is not supported yet
## Folder structure
+3 -3
View File
@@ -1,13 +1,13 @@
[package]
name = "tuono"
version = "0.2.1"
version = "0.3.1"
edition = "2021"
authors = ["V. Ageno <valerioageno@yahoo.it>"]
description = "The react/rust fullstack framework"
homepage = "https://github.com/Valerioageno/tuono"
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"
+1 -1
View File
@@ -165,7 +165,7 @@ fn outro(folder_name: String) {
}
println!("\nInstall the dependencies:");
println!("pnpm install");
println!("npm install");
println!("\nRun the local environment:");
println!("tuono dev");
+6 -48
View File
@@ -47,12 +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 tuono_lib::{tokio, Mode, Server, axum::Router, axum::routing::get};
use reqwest::Client;
const MODE: Mode = /*MODE*/;
@@ -61,52 +56,13 @@ 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"))
.fallback_service(ServeDir::new("out/client")
.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
}
"##;
@@ -154,7 +110,7 @@ impl Route {
}
Route {
module_import: module.as_str().to_string().replace('/', "_"),
module_import: module.as_str().to_string().replace('/', "_").to_lowercase(),
axum_route,
}
}
@@ -323,6 +279,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
@@ -334,6 +291,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)| {
+9 -6
View File
@@ -1,13 +1,13 @@
[package]
name = "tuono_lib"
version = "0.2.1"
version = "0.3.1"
edition = "2021"
authors = ["V. Ageno <valerioageno@yahoo.it>"]
description = "The react/rust fullstack framework"
homepage = "https://github.com/Valerioageno/tuono"
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"
@@ -18,14 +18,17 @@ name = "tuono_lib"
path = "src/lib.rs"
[dependencies]
ssr_rs = "0.5.4"
axum = "0.7.5"
ssr_rs = "0.5.5"
axum = {version = "0.7.5", features = ["json"]}
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.1"}
tuono_lib_macros = {path = "../tuono_lib_macros", version = "0.3.1"}
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"]}
+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::SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload)));
match result {
Ok(html) => Html(html),
_ => Html("500 internal server error".to_string()),
}
}
+10 -5
View File
@@ -1,14 +1,19 @@
pub mod manifest;
mod catch_all;
mod manifest;
mod mode;
mod payload;
mod request;
mod response;
mod server;
mod ssr;
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 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;
+50 -8
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())),
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(),
}
}
}
+53
View File
@@ -0,0 +1,53 @@
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;
const DEV_PUBLIC_DIR: &str = "public";
const PROD_PUBLIC_DIR: &str = "out/client";
pub struct Server {
router: Router,
mode: Mode,
}
impl Server {
pub fn init(router: Router, 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();
if self.mode == Mode::Dev {
println!("\nDevelopment app ready at http://localhost:3000/");
} else {
println!("\nProduction app ready at http://localhost:3000/");
}
let public_dir = if self.mode == Mode::Dev {
DEV_PUBLIC_DIR
} else {
PROD_PUBLIC_DIR
};
let router = self
.router
.to_owned()
.fallback_service(ServeDir::new(public_dir).fallback(get(catch_all)));
axum::serve(listener, router).await.unwrap();
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::{Mode, GLOBAL_MODE};
use crate::mode::{Mode, GLOBAL_MODE};
use lazy_static::lazy_static;
use ssr_rs::Ssr;
use std::cell::RefCell;
+3 -3
View File
@@ -1,12 +1,12 @@
[package]
name = "tuono_lib_macros"
version = "0.2.1"
version = "0.3.1"
edition = "2021"
description = "The react/rust fullstack framework"
homepage = "https://github.com/Valerioageno/tuono"
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"
+4 -4
View File
@@ -8,9 +8,9 @@ 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 tuono_lib::axum::extract::{State, Path};
use reqwest::Client;
#item
@@ -18,7 +18,7 @@ pub fn handler_core(_args: TokenStream, item: TokenStream) -> TokenStream {
pub async fn route(
Path(params): Path<HashMap<String, String>>,
State(client): State<Client>,
request: axum::extract::Request
request: tuono_lib::axum::extract::Request
) -> impl IntoResponse {
let pathname = &request.uri();
let headers = &request.headers();
@@ -31,7 +31,7 @@ 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
request: tuono_lib::axum::extract::Request
) -> impl IntoResponse{
let pathname = &request.uri();
let headers = &request.headers();
+39 -3
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)
@@ -53,7 +54,7 @@ $ tuono new tuono-tutorial
Get into the project folder and install the dependencies with:
```bash
$ pnpm install
$ npm install
```
Open it with your favourite code editor.
@@ -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
@@ -283,7 +284,7 @@ Create alongside the `PokemonLink.tsx` component the CSS module `PokemonLink.mod
}
```
> 💡 SASS is supported out of the box. Just install the processor in the devDependencies `pnpm i -D sass` and run again `tuono dev`
> 💡 SASS is supported out of the box. Just install the processor in the devDependencies `npm i -D sass` and run again `tuono dev`
Then import the styles into the `PokemonLink` component as following:
@@ -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 -5
View File
@@ -8,11 +8,7 @@ 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"
serde = { version = "1.0.202", features = ["derive"] }
reqwest = {version = "0.12.4", features = ["json"]}
+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::{Request, Response};
#[tuono_lib::handler]
async fn redirect_to_goat(_: Request<'_>, _: reqwest::Client) -> Response {
Response::Redirect("/pokemons/mewtwo".to_string())
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "tuono-lazy-fn-vite-plugin",
"version": "0.2.1",
"version": "0.3.1",
"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.1",
"version": "0.3.1",
"description": "The react/rust fullstack framework",
"scripts": {
"dev": "vite build --watch",
@@ -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: '',
}
}