loco-rs 0.16.1

The one-person framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! This module defines the [`AppRoutes`] struct that is responsible for
//! configuring routes in an Axum application. It allows you to define route
//! prefixes, add routes, and configure middlewares for the application.

use std::{fmt, sync::OnceLock};

use axum::Router as AXRouter;
use regex::Regex;

use crate::{
    app::{AppContext, Hooks},
    controller::{middleware::MiddlewareLayer, routes::Routes},
    Result,
};

static NORMALIZE_URL: OnceLock<Regex> = OnceLock::new();

fn get_normalize_url() -> &'static Regex {
    NORMALIZE_URL.get_or_init(|| Regex::new(r"/+").unwrap())
}

/// Represents the routes of the application.
#[derive(Clone)]
pub struct AppRoutes {
    prefix: Option<String>,
    routes: Vec<Routes>,
}

#[derive(Debug)]
pub struct ListRoutes {
    pub uri: String,
    pub actions: Vec<axum::http::Method>,
    pub method: axum::routing::MethodRouter<AppContext>,
}

impl fmt::Display for ListRoutes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let actions_str = self
            .actions
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(",");

        write!(f, "[{}] {}", actions_str, self.uri)
    }
}

impl AppRoutes {
    /// Create a new instance with the default routes.
    #[must_use]
    pub fn with_default_routes() -> Self {
        let routes = Self::empty().add_route(super::ping::routes());
        #[cfg(feature = "with-db")]
        let routes = routes.add_route(super::health::routes());

        routes
    }

    /// Create an empty instance.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            prefix: None,
            routes: vec![],
        }
    }

    #[must_use]
    pub fn collect(&self) -> Vec<ListRoutes> {
        self.get_routes()
            .iter()
            .flat_map(|controller| {
                let uri_parts = controller
                    .prefix
                    .as_ref()
                    .map_or_else(Vec::new, |prefix| vec![prefix.to_string()]);

                controller.handlers.iter().map(move |handler| {
                    let mut parts = uri_parts.clone();
                    parts.push(handler.uri.to_string());
                    let joined_parts = parts.join("/");

                    let normalized = get_normalize_url().replace_all(&joined_parts, "/");
                    let mut uri = if normalized == "/" {
                        normalized.to_string()
                    } else {
                        normalized
                            .strip_suffix('/')
                            .map_or_else(|| normalized.to_string(), ToString::to_string)
                    };

                    if !uri.starts_with('/') {
                        uri.insert(0, '/');
                    }

                    ListRoutes {
                        uri,
                        actions: handler.actions.clone(),
                        method: handler.method.clone(),
                    }
                })
            })
            .collect()
    }

    /// Get the prefix of the routes.
    #[must_use]
    pub fn get_prefix(&self) -> Option<&String> {
        self.prefix.as_ref()
    }

    /// Get the routes.
    #[must_use]
    pub fn get_routes(&self) -> &[Routes] {
        self.routes.as_ref()
    }

    /// Set a prefix for the routes. this prefix will be a prefix for all the
    /// routes.
    ///
    /// # Example
    ///
    /// In the following example you are adding api as a prefix for all routes
    ///
    /// ```rust
    /// use loco_rs::controller::AppRoutes;
    ///
    /// AppRoutes::with_default_routes().prefix("api");
    /// ```
    #[must_use]
    pub fn prefix(mut self, prefix: &str) -> Self {
        let mut prefix = prefix.to_owned();
        if !prefix.ends_with('/') {
            prefix.push('/');
        }
        if !prefix.starts_with('/') {
            prefix.insert(0, '/');
        }

        self.prefix = Some(prefix);

        self
    }

    /// Set a nested prefix for the routes. This prefix will be appended to any existing prefix.
    ///
    /// # Example
    ///
    /// In the following example, you are adding `api` as a prefix and then nesting `v1` within it:
    ///
    /// ```rust
    /// use loco_rs::controller::AppRoutes;
    /// use loco_rs::tests_cfg::*;
    ///
    /// let app_routes = AppRoutes::with_default_routes()
    ///      .prefix("api")
    ///      .add_route(controllers::auth::routes())
    ///      .nest_prefix("v1")
    ///      .add_route(controllers::home::routes());
    ///
    /// // This will result in routes like `/api/auth` and `/api/v1/home`
    /// ```
    #[must_use]
    pub fn nest_prefix(mut self, prefix: &str) -> Self {
        let prefix = self.prefix.as_ref().map_or_else(
            || prefix.to_owned(),
            |old_prefix| format!("{old_prefix}{prefix}"),
        );
        self = self.prefix(&prefix);

        self
    }

    /// Set a nested route with a prefix. This route will be added with the specified prefix.
    /// The prefix will only be applied to the routes given in this function.
    ///
    /// # Example
    ///
    /// In the following example, you are adding `api` as a prefix and then nesting a route within it:
    ///
    /// ```rust
    /// use axum::routing::get;
    /// use loco_rs::controller::{AppRoutes, Routes};
    ///
    /// let route = Routes::new().add("/notes", get(|| async { "notes" }));
    /// let app_routes = AppRoutes::with_default_routes()
    ///     .prefix("api")
    ///     .nest_route("v1", route);
    ///
    /// // This will result in routes with the prefix `/api/v1/notes`
    /// ```
    #[must_use]
    pub fn nest_route(mut self, prefix: &str, route: Routes) -> Self {
        let old_prefix = self.prefix.clone();
        self = self.nest_prefix(prefix);
        self = self.add_route(route);
        self.prefix = old_prefix;

        self
    }

    /// Set multiple nested routes with a prefix. These routes will be added with the specified prefix.
    /// The prefix will only be applied to the routes given in this function.
    ///
    /// # Example
    ///
    /// In the following example, you are adding `api` as a prefix and then nesting multiple routes within it:
    ///
    /// ```rust
    /// use axum::routing::get;
    /// use loco_rs::controller::{AppRoutes, Routes};
    ///
    /// let routes = vec![
    ///     Routes::new().add("/notes", get(|| async { "notes" })),
    ///     Routes::new().add("/users", get(|| async { "users" })),
    /// ];
    /// let app_routes = AppRoutes::with_default_routes()
    ///     .prefix("api")
    ///     .nest_routes("v1", routes);
    ///
    /// // This will result in routes with the prefix `/api/v1/notes` and `/api/v1/users`
    /// ```
    #[must_use]
    pub fn nest_routes(mut self, prefix: &str, routes: Vec<Routes>) -> Self {
        let old_prefix = self.prefix.clone();
        self = self.nest_prefix(prefix);
        self = self.add_routes(routes);
        self.prefix = old_prefix;

        self
    }

    /// Add a single route.
    #[must_use]
    pub fn add_route(mut self, mut route: Routes) -> Self {
        let routes_prefix = {
            if let Some(mut prefix) = self.prefix.clone() {
                let routes_prefix = route.prefix.clone().unwrap_or_default();

                prefix.push_str(routes_prefix.as_str());
                Some(prefix)
            } else {
                route.prefix.clone()
            }
        };

        if let Some(prefix) = routes_prefix {
            route = route.prefix(prefix.as_str());
        }

        self.routes.push(route);

        self
    }

    /// Add multiple routes.
    #[must_use]
    pub fn add_routes(mut self, mounts: Vec<Routes>) -> Self {
        for mount in mounts {
            self = self.add_route(mount);
        }

        self
    }

    #[must_use]
    pub fn middlewares<H: Hooks>(&self, ctx: &AppContext) -> Vec<Box<dyn MiddlewareLayer>> {
        H::middlewares(ctx)
            .into_iter()
            .filter(|m| m.is_enabled())
            .collect::<Vec<Box<dyn MiddlewareLayer>>>()
    }

    /// Add the routes to an existing Axum Router, and set a list of middlewares
    /// that configure in the [`config::Config`]
    ///
    /// # Errors
    /// Return an [`Result`] when could not convert the router setup to
    /// [`axum::Router`].
    #[allow(clippy::cognitive_complexity)]
    pub fn to_router<H: Hooks>(
        &self,
        ctx: AppContext,
        mut app: AXRouter<AppContext>,
    ) -> Result<AXRouter> {
        // IMPORTANT: middleware ordering in this function is opposite to what you
        // intuitively may think. when using `app.layer` to add individual middleware,
        // the LAST middleware is the FIRST to meet the outside world (a user request
        // starting), or "LIFO" order.
        // We build the "onion" from the inside (start of this function),
        // outwards (end of this function). This is why routes is first in coding order
        // here (the core of the onion), and request ID is amongst the last
        // (because every request is assigned with a unique ID, which starts its
        // "life").
        //
        // NOTE: when using ServiceBuilder#layer the order is FIRST to LAST (but we
        // don't use ServiceBuilder because it requires too complex generic typing for
        // this function). ServiceBuilder is recommended to save compile times, but that
        // may be a thing of the past as we don't notice any issues with compile times
        // using the router directly, and ServiceBuilder has been reported to give
        // issues in compile times itself (https://github.com/rust-lang/crates.io/pull/7443).
        //
        for router in self.collect() {
            tracing::info!("{}", router.to_string());
            app = app.route(&router.uri, router.method);
        }

        let middlewares = self.middlewares::<H>(&ctx);
        for mid in middlewares {
            app = mid.apply(app)?;
            tracing::info!(name = mid.name(), "+middleware");
        }
        let router = app.with_state(ctx);
        Ok(router)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{prelude::*, tests_cfg};
    use axum::http::Method;
    use insta::assert_debug_snapshot;
    use rstest::rstest;
    use std::vec;
    use tower::ServiceExt;

    async fn action() -> Result<Response> {
        format::json("loco")
    }

    #[test]
    fn can_load_app_route_from_default() {
        let routes = AppRoutes::with_default_routes().collect();

        for route in routes {
            assert_debug_snapshot!(
                format!("[{}]", route.uri.replace('/', "[slash]")),
                format!("{:?} {}", route.actions, route.uri)
            );
        }
    }

    #[test]
    fn can_load_empty_app_routes() {
        assert_eq!(AppRoutes::empty().collect().len(), 0);
    }

    #[test]
    fn can_load_routes() {
        let router_without_prefix = Routes::new().add("/", get(action));
        let normalizer = Routes::new()
            .prefix("/normalizer")
            .add("no-slash", get(action))
            .add("/", post(action))
            .add("//loco///rs//", delete(action))
            .add("//////multiple-start", head(action))
            .add("multiple-end/////", trace(action));

        let app_router = AppRoutes::empty()
            .add_route(router_without_prefix)
            .add_route(normalizer)
            .add_routes(vec![
                Routes::new().add("multiple1", put(action)),
                Routes::new().add("multiple2", options(action)),
                Routes::new().add("multiple3", patch(action)),
            ]);

        for route in app_router.collect() {
            assert_debug_snapshot!(
                format!("[{}]", route.uri.replace('/', "[slash]")),
                format!("{:?} {}", route.actions, route.uri)
            );
        }
    }

    #[test]
    fn can_load_routes_with_root_prefix() {
        let router_without_prefix = Routes::new()
            .add("/loco", get(action))
            .add("loco-rs", get(action));

        let app_router = AppRoutes::empty()
            .prefix("api")
            .add_route(router_without_prefix);

        for route in app_router.collect() {
            assert_debug_snapshot!(
                format!("[{}]", route.uri.replace('/', "[slash]")),
                format!("{:?} {}", route.actions, route.uri)
            );
        }
    }

    #[test]
    fn can_nest_prefix() {
        let app_router = AppRoutes::empty().prefix("api").nest_prefix("v1");

        assert_eq!(app_router.get_prefix().unwrap(), "/api/v1/");
    }

    #[test]
    fn can_nest_route() {
        let route = Routes::new().add("/notes", get(action));
        let app_router = AppRoutes::empty().prefix("api").nest_route("v1", route);

        let routes = app_router.collect();
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0].uri, "/api/v1/notes");
    }

    #[test]
    fn can_nest_routes() {
        let routes = vec![
            Routes::new().add("/notes", get(action)),
            Routes::new().add("/users", get(action)),
        ];
        let app_router = AppRoutes::empty().prefix("api").nest_routes("v1", routes);

        for route in app_router.collect() {
            assert_debug_snapshot!(
                format!("[{}]", route.uri.replace('/', "[slash]")),
                format!("{:?} {}", route.actions, route.uri)
            );
        }
    }

    #[rstest]
    #[case(Method::GET, get(action))]
    #[case(Method::POST, post(action))]
    #[case(Method::DELETE, delete(action))]
    #[case(Method::HEAD, head(action))]
    #[case(Method::OPTIONS, options(action))]
    #[case(Method::PATCH, patch(action))]
    #[case(Method::POST, post(action))]
    #[case(Method::PUT, put(action))]
    #[case(Method::TRACE, trace(action))]
    #[tokio::test]
    async fn can_request_method(
        #[case] http_method: Method,
        #[case] method: axum::routing::MethodRouter<AppContext>,
    ) {
        let router_without_prefix = Routes::new().add("/loco", method);

        let app_router = AppRoutes::empty().add_route(router_without_prefix);

        let ctx = tests_cfg::app::get_app_context().await;
        let router = app_router
            .to_router::<tests_cfg::db::AppHook>(ctx, axum::Router::new())
            .unwrap();

        let req = axum::http::Request::builder()
            .uri("/loco")
            .method(http_method)
            .body(axum::body::Body::empty())
            .unwrap();

        let response = router.oneshot(req).await.unwrap();
        assert!(response.status().is_success());
    }
}