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
//! Tide Fluent Routes is a fluent api to define routes for the Tide HTTP framework.
//! At the moment it supports setting up paths, you can integrate middleware at any place in the
//! route-tree and you can integrate endpoints.
//! Some things that are possible with Tide-native routes are not (yet) possible;
//! - middleware does not work for now, there is support missing for this in Tide
//! - Tide prefix routes are not implemented
//! - you can not nest Tide servers
//! - serving directories is not possible but a version of this is planned
//!
//! To use this you can import Tide Fluent Routes with `use tide_fluent_routes::prelude::* it
//! introduces the `register` extension method on the `Tide::Server to register routes from a
//! RouteBuilder.
//! A RouteBuilder can be initialized using the `route()` method.
//! You can register simple endpoints like this;
//! ```rust
//! # use tide::{Request, Result};
//! # use tide_fluent_routes::prelude::*;
//! # pub async fn endpoint(_: Request<()>) -> Result {
//! #     todo!()
//! # }
//! use tide_fluent_routes::*;
//!
//! let mut server = tide::Server::new();
//!
//! server.register(
//!    root()
//!        .get(endpoint)
//!        .post(endpoint),
//! );
//! ```
//! Fluent Routes follows conventions from Tide. All HTTP verbs are supported the same way. Paths
//! can be extended using `at` but this method takes a router closure that allows building the route
//! as a tree.
//! A complete route tree can be defined like this;
//! ```rust
//! # use tide::{Request, Result};
//! # use tide_fluent_routes::prelude::*;
//! # pub async fn endpoint(_: Request<()>) -> Result {
//! #     todo!()
//! # }
//! # let mut server = tide::Server::new();
//!
//! server.register(
//!     root()
//!         .get(endpoint)
//!         .post(endpoint)
//!         .at("api/v1", |route| {
//!             route
//!                 .get(endpoint)
//!                 .post(endpoint)
//!         })
//!         .at("api/v2", |route| {
//!             route
//!                 .get(endpoint)
//!                 .post(endpoint)
//!         }),
//! );
//! ```
//! This eliminates the need to introduce variables for partial pieces of your route tree.
//!
//! Another problem with Tide routes is that middleware that is only active for certain routes can
//! be difficult to maintain. Adding middleware to a tree is easy, and its very clear where the
//! middleware is applied and where not; (this is still a prototype and middleware is not actually
//! added right now)
//! ```rust
//! # use std::{future::Future, pin::Pin};
//! # use tide::{Next, Request, Result};
//! # use tide_fluent_routes::prelude::*;
//! # pub async fn endpoint(_: Request<()>) -> Result {
//! #     todo!()
//! # }
//! # pub fn dummy_middleware<'a>(
//! #     request: Request<()>,
//! #     next: Next<'a, ()>,
//! # ) -> Pin<Box<dyn Future<Output = Result> + Send + 'a>> {
//! #     Box::pin(async { Ok(next.run(request).await) })
//! # }
//! # let mut server = tide::Server::new();
//! server.register(
//!     root()
//!         .get(endpoint)
//!         .post(endpoint)
//!         .at("api/v1", |route| {
//!             route
//!                 .with(dummy_middleware, |route| {
//!                     route.get(endpoint)
//!                 })
//!                .post(endpoint)
//!         })
//!         .at("api/v2", |route| {
//!             route
//!                 .get(endpoint)
//!                 .get(endpoint)
//!         }),
//! );
//! ```

// Turn on warnings for some lints
#![warn(
    missing_debug_implementations,
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unreachable_pub,
    unused_import_braces,
    unused_qualifications
)]

mod path;
pub mod routebuilder;
pub mod router;

use crate::path::Path;
use routebuilder::RouteBuilder;
use std::collections::HashMap;
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::sync::Arc;
use tide::http::Method;
use tide::utils::async_trait;
use tide::{Endpoint, Middleware};

struct BoxedEndpoint<State>(Box<dyn Endpoint<State>>);

impl<State> Debug for BoxedEndpoint<State> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter.debug_struct("BoxedEndpoint").finish()
    }
}

impl<State: Clone + Send + Sync + 'static> BoxedEndpoint<State> {
    /// Wrap an endpoint in a BoxedEndpoint
    fn new(endpoint: impl Endpoint<State>) -> Self {
        Self(Box::new(endpoint))
    }
}

#[async_trait]
impl<State: Clone + Send + Sync + 'static> Endpoint<State> for BoxedEndpoint<State> {
    async fn call(&self, req: tide::Request<State>) -> tide::Result {
        self.0.call(req).await
    }
}

/// Start building a route. Returns a RouteBuilder for the root of your route
pub fn root<State>() -> RouteSegment<State> {
    RouteSegment {
        route: RouteSegmentKind::Root,
        branches: Vec::new(),
        endpoints: HashMap::new(),
    }
}

/// A Builder for Tide routes. RouteBuilders can be composed into a tree that represents the tree of
/// path segments, middleware and endpoints that defines the routes in a Tide application. This tree
/// can then be returned as a list of routes to each of the endpoints.
#[derive(Debug)]
pub struct RouteSegment<State> {
    route: RouteSegmentKind<State>,
    branches: Vec<RouteSegment<State>>,
    endpoints: HashMap<Option<Method>, BoxedEndpoint<State>>,
}

enum RouteSegmentKind<State> {
    Root,
    Path(String),
    Middleware(Arc<dyn Middleware<State>>),
}

impl<State> RouteSegmentKind<State> {
    /// Apply the path or middleware in to the endpoint
    fn apply_to(&self, endpoint: EndpointDescriptor<State>) -> EndpointDescriptor<State> {
        let EndpointDescriptor(path, method, mut middleware, endpoint) = endpoint;

        match self {
            RouteSegmentKind::Root => EndpointDescriptor(path, method, middleware, endpoint),
            RouteSegmentKind::Path(segment) => {
                EndpointDescriptor(path.prepend(segment), method, middleware, endpoint)
            }
            RouteSegmentKind::Middleware(ware) => {
                middleware.push(ware.clone());
                EndpointDescriptor(path, method, middleware, endpoint)
            }
        }
    }
}

impl<State> Debug for RouteSegmentKind<State> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        match self {
            RouteSegmentKind::Root => write!(formatter, "RouteSegmentKind::Root"),
            RouteSegmentKind::Path(path) => write!(formatter, "RouteSegmentKind::Path({})", path),
            RouteSegmentKind::Middleware(_) => write!(formatter, "RouteSegmentKind::Middleware"),
        }
    }
}

impl<State: Clone + Send + Sync + 'static> RouteSegment<State> {
    /// Add a branch, helper method for at and with methods
    fn add_branch<R: Fn(Self) -> Self>(mut self, spec: RouteSegmentKind<State>, routes: R) -> Self {
        self.branches.push(routes(RouteSegment {
            route: spec,
            branches: Vec::new(),
            endpoints: HashMap::new(),
        }));
        self
    }

    fn build(self) -> Vec<EndpointDescriptor<State>> {
        let local_endpoints: Vec<EndpointDescriptor<State>> = self
            .endpoints
            .into_iter()
            .map(|(method, endpoint)| EndpointDescriptor(Path::new(), method, Vec::new(), endpoint))
            .collect();

        let sub_endpoints: Vec<EndpointDescriptor<State>> = self
            .branches
            .into_iter()
            .flat_map(RouteSegment::build)
            .collect();

        let route = self.route;
        local_endpoints
            .into_iter()
            .chain(sub_endpoints.into_iter())
            .map(|descriptor| route.apply_to(descriptor))
            .collect()
    }
}

impl<State: Clone + Send + Sync + 'static> RouteBuilder<State> for RouteSegment<State> {
    /// Add an endpoint
    fn method(mut self, method: Method, endpoint: impl Endpoint<State>) -> Self {
        self.endpoints
            .insert(Some(method), BoxedEndpoint::new(endpoint));
        self
    }

    fn all(mut self, endpoint: impl Endpoint<State>) -> Self {
        self.endpoints.insert(None, BoxedEndpoint::new(endpoint));
        self
    }

    /// Add sub-routes for a path segment
    fn at<R: Fn(Self) -> Self>(self, path: &str, routes: R) -> Self {
        self.add_branch(RouteSegmentKind::Path(path.to_string()), routes)
    }

    /// Add sub-routes for a middleware
    fn with<M: Middleware<State>, R: Fn(Self) -> Self>(self, middleware: M, routes: R) -> Self {
        self.add_branch(RouteSegmentKind::Middleware(Arc::new(middleware)), routes)
    }
}

/// Describes all information for registering an endpoint, the path to it, its middleware
/// and its HttpMethod
pub(crate) struct EndpointDescriptor<State>(
    Path,
    Option<Method>,
    Vec<Arc<dyn Middleware<State>>>,
    BoxedEndpoint<State>,
);

impl<State> Debug for EndpointDescriptor<State> {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter.debug_struct("EndpointDescriptor").finish()
    }
}

/// Import types to use tide_fluent_routes
pub mod prelude {
    pub use super::routebuilder::{RouteBuilder, RouteBuilderExt};
    pub use super::router::Router;
    pub use super::{root, RouteSegment};
    pub use tide::http::Method;
}

#[cfg(test)]
mod test {
    use super::prelude::*;

    #[test]
    fn should_build_single_endpoint() {
        let routes: Vec<_> = root::<()>().get(|_| async { Ok("") }).build();

        assert_eq!(routes.len(), 1);
    }

    #[test]
    fn should_build_multiple_endpoints() {
        let routes: Vec<_> = root::<()>()
            .get(|_| async { Ok("") })
            .post(|_| async { Ok("") })
            .build();

        assert_eq!(routes.len(), 2);
    }

    #[test]
    fn should_build_sub_endpoints() {
        let routes: Vec<_> = root::<()>()
            .at("sub_path", |r| {
                r.get(|_| async { Ok("") }).post(|_| async { Ok("") })
            })
            .build();

        assert_eq!(routes.len(), 2);
    }

    #[test]
    fn should_build_endpoint_path() {
        let routes: Vec<_> = root::<()>()
            .at("path", |r| r.at("subpath", |r| r.get(|_| async { Ok("") })))
            .build();

        assert_eq!(routes.len(), 1);
        assert_eq!(routes.get(0).unwrap().1, Some(Method::Get));
        assert_eq!(
            routes.get(0).unwrap().0.to_string(),
            "path/subpath".to_string()
        );
    }
}