@whi/cf-routing - v0.2.0
    Preparing search index...

    Class WorkerRouter<E>

    Router for Cloudflare Workers with class-based handlers and automatic error handling

    const router = new WorkerRouter<Env>('my-worker')
    .defineRouteHandler('/health', HealthHandler)
    .get('/ping', async () => ({ message: 'pong' }))
    .build();

    export default {
    async fetch(request, env, ctx) {
    return router.fetch(request, env, ctx);
    }
    };

    Type Parameters

    • E extends Env

      Environment type extending base Env interface

    Index

    Constructors

    • Create a new WorkerRouter

      Type Parameters

      Parameters

      • name: string = 'unnamed'

        Router name (default: 'unnamed')

      • ...args: [RouterOptions<unknown, any[]>?]

        Additional arguments passed to itty-router

      Returns WorkerRouter<E>

    Properties

    name: string

    Router name for logging

    log: Logger

    Logger instance

    router: RouterType<unknown>

    Underlying itty-router instance

    Methods

    post

    • Register a class-based route handler for all HTTP methods

      Automatically registers GET, POST, PUT, DELETE, and PATCH methods from the handler class.

      Parameters

      • path: string

        Route path pattern (e.g., '/users/:id')

      • handler_cls: new (...args: [path: string, options?: { log?: Logger }]) => RouteHandler<E>

        RouteHandler class to instantiate

      Returns WorkerRouter<E>

      This router instance for chaining

      class UserHandler extends RouteHandler<Env, { id: string }> {
      async get(request, env, params) {
      return { userId: params.id };
      }
      }

      router.defineRouteHandler('/users/:id', UserHandler);
    • Build the router and add 404 handler

      Must be called before using the router in a Worker's fetch handler.

      Returns RouterType<unknown, any[], unknown>

      The underlying itty-router instance

      const router = new WorkerRouter('my-worker')
      .defineRouteHandler('/health', HealthHandler)
      .build();

      export default {
      async fetch(request, env, ctx) {
      return router.fetch(request, env, ctx);
      }
      };