worker_route_macro/lib.rs
1#![warn(clippy::pedantic, clippy::nursery)]
2#![allow(clippy::use_self)]
3extern crate proc_macro;
4extern crate quote;
5extern crate syn;
6
7mod error;
8mod expand;
9mod method;
10mod route;
11mod transform;
12mod wrapper;
13use method::Method;
14use paste::paste;
15use proc_macro::TokenStream;
16
17macro_rules! route_method {
18 ($variant:ident, $method:ident) => {
19 paste! {
20 #[doc = "A macro that creates route handler with [`worker::Router::" $method "" "`]" "(https://docs.rs/worker/latest/worker/struct.Router.html#method." "" $method """)"]
21 ///
22 #[doc = "[`worker::Router::" $method "_async" "`]" "(https://docs.rs/worker/latest/worker/struct.Router.html#method." "" $method "_async"") will be used if the handler is an async fn."]
23 ///
24 /// # Usage
25 /// ```text
26 #[doc = " #[" $method "" r#"("/path")]"#]
27 /// ```
28 ///
29 /// # Attributes
30 /// - `"path"`: Worker's path.
31 /// - `Option<cors>`: Wrap a struct that implements `worker_route::MwService`.
32 /// - `Option<lazy_cors>`: Wrap a lazy initialized Cors.
33 /// - `Option<wrap>`: Register an options handler with the provided cors. Defaults to `None`.
34 ///
35 /// # Examples
36 /// ```
37 /// use worker::{Result, Request, RouteContext, Response};
38 #[doc = "use worker_route::" $method ";"]
39 ///
40 #[doc = "#[" $method "" r#"("/path")]"#]
41 /// async fn foo(req: Request, ctx: RouteContext<()>) -> Result<Response>{
42 /// Response::empty()
43 /// }
44 /// ```
45 #[proc_macro_attribute]
46 pub fn $method(attrs: TokenStream, items: TokenStream) -> TokenStream {
47 route::with_method::<{ Method::$variant as _ }>(attrs, items)
48 }
49 }
50 }
51}
52
53/// A macro that creates route handler with multiple methods.
54///
55/// # Usage
56/// ```text
57/// #[route("path", method = "method", cors = "cors", lazy_cors = "lazy_cors", wrap)]
58/// ```
59///
60/// # Attributes
61/// - `"path"`: Worker's path.
62/// - `method`: An array of methods or a method in string literal.
63/// - `Option<cors>`: Wrap a struct that implements `worker_route::MwService`.
64/// - `Option<lazy_cors>`: Wrap a lazy initialized Cors.
65/// - `Option<wrap>`: Register an options handler with the provided cors. Defaults to `None`.
66///
67/// # Examples
68/// ```
69/// use worker::{Result, Request, RouteContext, Response};
70/// use worker_route::route;
71///
72/// #[route("/path", method = "get", method = "post")]
73/// async fn foo(req: Request, ctx: RouteContext<()>) -> Result<Response> {
74/// Response::empty()
75/// }
76/// ```
77#[proc_macro_attribute]
78pub fn route(attrs: TokenStream, items: TokenStream) -> TokenStream {
79 route::with_method::<{ Method::Default as _ }>(attrs, items)
80}
81
82route_method!(Delete, delete);
83route_method!(Get, get);
84route_method!(Head, head);
85route_method!(Options, options);
86route_method!(Patch, patch);
87route_method!(Post, post);
88route_method!(Put, put);