worker_route

Trait Service

Source
pub trait Service {
    // Required method
    fn service<F: FnOnce(Self) -> Self>(self, f: F) -> Self
       where Self: Sized;
}
Expand description

Implemented for worker::Router to run external route configuration.

This trait is useful for splitting the configuration to a different module.

§Example

use serde::{Deserialize, Serialize};
use worker::{event, Env, Request, Response, ResponseBody, Result, RouteContext, Router};
use worker_route::{get, Service, Configure, Query};

#[derive(Debug, Serialize, Deserialize)]
struct Bar {
    bar: String,
}

#[get("/bar")]
async fn bar(req: Query<Bar>, _: RouteContext<()>) -> Result<Response> {
    Response::from_body(ResponseBody::Body(req.into_inner().bar.as_bytes().into()))
}

#[derive(Debug, Serialize, Deserialize)]
struct Foo {
    foo: String,
}

#[get("/foo")]
async fn foo(req: Query<Foo>, _: RouteContext<()>) -> Result<Response> {
    Response::from_body(ResponseBody::Body(req.into_inner().foo.as_bytes().into()))
}

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: usize,
}

#[get("/person/:name/:age")]
async fn person(req: Query<Person>, _: RouteContext<()>) -> Result<Response> {
    Response::from_json(&req.into_inner())
}

// wrapper function
fn init_routes(router: Router<'_, ()>) -> Router<'_, ()> {
    router.configure(bar).configure(foo).configure(person)
}

#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
    let router = Router::new();
    // before
    // router.configure(bar).configure(foo).configure(person).run(req, env).await
    // after
    // router.service(init_routes).run(req, env).await
    router.service(init_routes).run(req, env).await
}

Required Methods§

Source

fn service<F: FnOnce(Self) -> Self>(self, f: F) -> Self
where Self: Sized,

Implementations on Foreign Types§

Source§

impl<D> Service for Router<'_, D>

Source§

fn service<F: FnOnce(Self) -> Self>(self, f: F) -> Self

Implementors§