zapient 0.0.0

Lightweight web stack
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Copyright (c) 2024 Zensical <contributors@zensical.org>

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

// ----------------------------------------------------------------------------

//! Router.

use std::str::FromStr;

use crate::handler::matcher::Route;
use crate::handler::stack::{self, Stack};
use crate::handler::{Error, Result, Scope, TryIntoHandler};
use crate::http::Method;
use crate::middleware::{Middleware, TryIntoMiddleware};

// Re-export for convenient usage with routers
pub use crate::handler::matcher::Params;

mod action;
mod routes;

pub use action::Action;
use routes::Routes;

// ----------------------------------------------------------------------------
// Enums
// ----------------------------------------------------------------------------

/// Builder.
///
/// Routers are built using a combination of stacks and routes, which can be
/// combined into a single stack when converting with [`TryIntoMiddleware`].
#[derive(Debug)]
enum Builder {
    /// Stack builder.
    Stack(stack::Builder),
    /// Routes builder.
    Routes(routes::Builder),
}

// ----------------------------------------------------------------------------
// Structs
// ----------------------------------------------------------------------------

/// Router.
///
/// Routers allow to scope specific actions to a combination of HTTP methods
/// and path patterns, making them essentially a specialization of [`Stack`].
/// Additionally, routers allow for the addition of middlewares, which are
/// grouped into stacks, and can be defined before and after routes.
#[derive(Debug)]
pub struct Router {
    /// Builders.
    builders: Vec<Builder>,
    /// Base path.
    path: String,
}

// ----------------------------------------------------------------------------
// Implementations
// ----------------------------------------------------------------------------

impl Router {
    /// Creates a router.
    ///
    /// The given path is prepended to all routes that are created as part of
    /// the router. Using [`Router::default`] is equivalent to passing `/`.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::router::Router;
    ///
    /// // Create router
    /// let router = Router::new("/");
    /// ```
    pub fn new<P>(path: P) -> Self
    where
        P: Into<String>,
    {
        Self {
            builders: Vec::new(),
            path: path.into(),
        }
    }

    /// Adds a `GET` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .get("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn get<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Get, path, action)
    }

    /// Adds a `POST` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .post("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn post<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Post, path, action)
    }

    /// Adds a `PUT` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .put("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn put<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Put, path, action)
    }

    /// Adds a `DELETE` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .delete("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn delete<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Delete, path, action)
    }

    /// Adds a `PATCH` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .patch("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn patch<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Patch, path, action)
    }

    /// Adds a `HEAD` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .head("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn head<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Head, path, action)
    }

    /// Adds a `OPTIONS` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .options("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn options<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Options, path, action)
    }

    /// Adds a `TRACE` route to the router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::http::{Request, Response};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and add route
    /// let router = Router::default()
    ///     .trace("/", |req: Request, params: Params| {
    ///         Response::default()
    ///     });
    /// ```
    #[inline]
    #[must_use]
    pub fn trace<P, A>(self, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        self.route(Method::Trace, path, action)
    }

    /// Adds a middleware to the router.
    ///
    /// Middlewares can be added at any point in the router stack, including
    /// before or after routes. This allows for flexible routing and middleware
    /// combinations, as routes are themselves combines into middlewares, when
    /// the router is converted into a middleware.
    ///
    /// Anything that can be converted into a [`Middleware`] can be added to
    /// the stack, including middlewares, routers, stacks and closures.
    ///
    /// # Errors
    ///
    /// Errors returned by [`TryIntoMiddleware`] are passed through.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use zapient::handler::Handler;
    /// use zapient::http::{Method, Request, Response, Status};
    /// use zapient::router::Router;
    ///
    /// // Create router with middleware
    /// let stack = Router::default()
    ///     .with(|req: Request, next: &dyn Handler| {
    ///         if req.method == Method::Get && req.uri.path == "/coffee" {
    ///             Response::new().status(Status::ImATeapot)
    ///         } else {
    ///             next.handle(req)
    ///         }
    ///     });
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with<M>(mut self, middleware: M) -> Self
    where
        M: TryIntoMiddleware,
    {
        // Consecutive middlewares are grouped into stacks, so we must ensure
        // that the current item is a stack builder, and add the middleware
        if let Some(Builder::Stack(builder)) = self.builders.last_mut() {
            builder.push(middleware);
        } else {
            let mut builder = Stack::new();
            builder.push(middleware);
            self.builders.push(Builder::Stack(builder));
        }

        // Return self for chaining
        self
    }

    /// Adds a route to the router.
    fn route<P, A>(mut self, method: Method, path: P, action: A) -> Self
    where
        P: Into<String>,
        A: Action,
    {
        // Consecutive routes are grouped into matchers, so we must ensure
        // that the current item is a routes builder, and add the route
        if let Some(Builder::Routes(builder)) = self.builders.last_mut() {
            builder.add(method, path, action);
        } else {
            let mut builder = Routes::builder();
            builder.add(method, path, action);
            self.builders.push(Builder::Routes(builder));
        }

        // Return self for chaining
        self
    }
}

// ----------------------------------------------------------------------------
// Trait implementations
// ----------------------------------------------------------------------------

impl TryIntoMiddleware for Router {
    type Output = Stack;

    /// Attempts to convert the router into a middleware.
    ///
    /// # Errors
    ///
    /// In case conversion fails, an [`Error`][] is returned.
    ///
    /// [`Error`]: crate::handler::Error
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use zapient::handler::Scope;
    /// use zapient::http::{Request, Response, Status};
    /// use zapient::middleware::TryIntoMiddleware;
    /// use zapient::router::{Router, Params};
    ///
    /// // Create scope
    /// let scope = Scope::default();
    ///
    /// // Create router and convert into middleware
    /// let router = Router::default()
    ///     .get("/coffee", |req: Request, params: Params| {
    ///         Response::new().status(Status::ImATeapot)
    ///     })
    ///     .try_into_middleware(&scope)?;
    /// # Ok(())
    /// # }
    /// ```
    fn try_into_middleware(self, scope: &Scope) -> Result<Self::Output> {
        let path = Route::from_str(&self.path)
            .map_err(|err| Error::Matcher(err.into()))?;

        // Join the parent scope with the scope derived from the router's base
        // path, which is then used for constructing routes and stacks
        let scope = scope.join(path);

        // Transform builders into middlewares - routers can host builders for
        // stacks and routes, both of which are converted into middlewares, and
        // then collected into a stack that can be converted into a handler.
        // Routes are validated and checked during conversion.
        let iter = self.builders.into_iter().map(|item| match item {
            // Convert stack into middleware
            Builder::Stack(builder) => builder
                .try_into_middleware(&scope)
                .map(|middleware| Box::new(middleware) as Box<dyn Middleware>),

            // Convert routes into middleware
            Builder::Routes(builder) => builder
                .try_into_middleware(&scope)
                .map(|middleware| Box::new(middleware) as Box<dyn Middleware>),
        });

        // Collect middlewares into a stack
        iter.collect()
    }
}

impl TryIntoHandler for Router {
    type Output = Stack;

    /// Attempts to convert the router into a handler.
    ///
    /// This method is equivalent to calling [`Router::try_into_middleware`]
    /// with [`Scope::default`], scoping all middlewares and routes to `/`.
    ///
    /// # Errors
    ///
    /// In case conversion fails, an [`Error`][] is returned.
    ///
    /// [`Error`]: crate::handler::Error
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use zapient::handler::TryIntoHandler;
    /// use zapient::http::{Request, Response, Status};
    /// use zapient::router::{Router, Params};
    ///
    /// // Create router and convert into handler
    /// let router = Router::default()
    ///     .get("/coffee", |req: Request, params: Params| {
    ///         Response::new().status(Status::ImATeapot)
    ///     })
    ///     .try_into_handler()?;
    /// # Ok(())
    /// # }
    /// ```
    fn try_into_handler(self) -> Result<Self::Output> {
        let scope = Scope::default();
        self.try_into_middleware(&scope)
    }
}

// ----------------------------------------------------------------------------

impl Default for Router {
    /// Creates a default router.
    ///
    /// # Examples
    ///
    /// ```
    /// use zapient::router::Router;
    ///
    /// // Create router
    /// let router = Router::default();
    /// ```
    fn default() -> Self {
        Self {
            builders: Vec::default(),
            path: String::from("/"),
        }
    }
}