Skip to content

Commit 35e1ba6

Browse files
authored
Fix Some Router Behaviour (yewstack#2107)
* Add Redirect Comp. * Fix router behaviour. * Fix output. * Fix pr-flow. * Remove Redirect. * Readd 77b46bf.
1 parent f2a0d61 commit 35e1ba6

File tree

2 files changed

+61
-10
lines changed

2 files changed

+61
-10
lines changed
Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::borrow::Cow;
2+
13
use crate::utils::{base_url, strip_slash_suffix};
24
use crate::Routable;
35

@@ -9,16 +11,14 @@ pub fn build_router<R: Routable>() -> Router {
911
let base = base_url();
1012
let mut router = Router::new();
1113
R::routes().iter().for_each(|path| {
12-
match &base {
13-
Some(base) => {
14-
let route = format!("{}{}", base, path);
15-
let route = strip_slash_suffix(&route);
16-
router.add(route, path.to_string());
17-
}
18-
_ => {
19-
router.add(path, path.to_string());
20-
}
14+
let route = match base {
15+
Some(ref base) => Cow::from(format!("{}{}", base, path)),
16+
None => (*path).into(),
2117
};
18+
19+
let stripped_route = strip_slash_suffix(&route);
20+
21+
router.add(stripped_route, path.to_string());
2222
});
2323

2424
router
@@ -30,7 +30,8 @@ pub fn recognize_with_router<R: Routable>(router: &Router, pathname: &str) -> Op
3030
let matched = router.recognize(pathname);
3131

3232
match matched {
33-
Ok(matched) => R::from_path(matched.handler(), &matched.params().into_iter().collect()),
33+
Ok(matched) => R::from_path(matched.handler(), &matched.params().into_iter().collect())
34+
.or_else(R::not_found_route),
3435
Err(_) => R::not_found_route(),
3536
}
3637
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
2+
use yew_router::prelude::*;
3+
4+
wasm_bindgen_test_configure!(run_in_browser);
5+
6+
#[test]
7+
fn router_always_404() {
8+
#[derive(Routable, Debug, Clone, PartialEq)]
9+
enum AppRoute {
10+
#[at("/")]
11+
Home,
12+
#[at("/:id")]
13+
Article { id: u64 },
14+
#[at("/404")]
15+
#[not_found]
16+
NotFound,
17+
}
18+
19+
assert_eq!(
20+
Some(AppRoute::NotFound),
21+
AppRoute::recognize("/not/matched/route")
22+
);
23+
assert_eq!(
24+
Some(AppRoute::NotFound),
25+
AppRoute::recognize("/not-matched-route")
26+
);
27+
}
28+
29+
#[test]
30+
fn router_trailing_slash() {
31+
#[derive(Routable, Debug, Clone, PartialEq)]
32+
enum AppRoute {
33+
#[at("/")]
34+
Home,
35+
#[at("/category/:name/")]
36+
Category { name: String },
37+
#[at("/:id")]
38+
Article { id: u64 },
39+
#[at("/404")]
40+
#[not_found]
41+
NotFound,
42+
}
43+
44+
assert_eq!(
45+
Some(AppRoute::Category {
46+
name: "cooking-recipes".to_string()
47+
}),
48+
AppRoute::recognize("/category/cooking-recipes/")
49+
);
50+
}

0 commit comments

Comments
 (0)