Skip to main content
Module

x/keywork/mod.ts>Router.KeyworkRouter

A library for building V8 Isolate web apps on Cloudflare Workers, Deno, and Node.JS
Go to Latest
class Router.KeyworkRouter
implements Fetcher<BoundAliases>, Disposable
import { Router } from "https://deno.land/x/keywork@v6.0.1/mod.ts";
const { KeyworkRouter } = Router;

Routes incoming HTTP requests from the user's browser to your app's route endpoints.

Keywork Documentation

Keywork API

Constructors

new
KeyworkRouter(options?: KeyworkRouterOptions)

Type Parameters

optional
BoundAliases = { }

Properties

protected
$routesEndpoint: RouteRequestHandler<BoundAliases>
protected
readonly
routesByVerb: Map<RouterMethod, ParsedRoute<BoundAliases>[]>

This router's known routes, categorized by their normalized HTTP method verbs into arrays of route handlers.

e.g.

GET: [{'/', routeHandler1}, {'/foo/' routeHandler2}, {'/bar/', routeHandler3}...]
POST: [{'/', routeHandler1}, {'/foo/' routeHandler2}, {'/bar/', routeHandler3}...]
...etc

Route handlers are prioritized in order of insertion, however, a handler can act as middleware by continuing the chain by returning next()

protected
terminateMiddleware: () => unknown
displayName: string

A display name used for debugging and log messages.

The Worker's primary incoming fetch handler.

This delegates to a method-specific handler you define, such as KeyworkRouter#get. Generally, KeyworkRouter#fetch should not be used within your app. This is instead automatically called by the Worker runtime when an incoming request is received.

readonly
includeDebugHeaders: boolean
readonly
logger: Logger

A server-side logger.

readonly
reactOptions: ReactRendererOptions
readonly
[kInstance]

Methods

protected
applyHeaders(response: globalThis.Response): globalThis.Response

Applies the default headers for a given Keywork request.

Collates the known routes by HTTP method verb.

$prettyPrintRoutes(routesByHttpMethod?): void

Outputs the known routes to the console.

all<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming all HTTP requests.

This will always be a higher priority than an explicitly defined method handler. If you're creating a router as middleware, KeyworkRouter#all can be especially useful for intercepting incoming requests.

appendMethodRoutes(
normalizedVerb: RouterMethod,
urlPatternLike: URLPatternLike,
...fetchersLike: Array<Fetcher<BoundAliases> | RouteRequestHandler<BoundAliases, any, any>>,
): void

Given a normalized HTTP method verb, create a method handler. This is mostly for internal use.

delete<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming DELETE requests.

The HTTP DELETE request method deletes the specified resource.

dispose(reason?)
get<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming GET requests.

The HTTP GET method requests a representation of the specified resource. Requests using GET should only be used to request data. The params object in the IsomorphicFetchEvent contains matched URL patterns which can be used to pass routing data from a client.

head<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming HEAD requests.

The HTTP HEAD method requests the headers that would be returned if the HEAD request's URL was instead requested with the HTTP GET method. For example, if a URL might produce a large download, a HEAD request could read its Content-Length header to check the filesize without actually downloading the file.

match<BoundAliases = { }>(parsedRoutes: ParsedRoute<BoundAliases>[], matchingAgainst: URLPatternInput): RouteMatch<BoundAliases>[]

Finds the matching routes for a given pathname.

options<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming OPTIONS requests.

The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (*) to refer to the entire server.

patch<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming PATCH requests.

post<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming POST requests.

The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.

put<ExpectedParams = { }, Data = { }>(...args: Parameters<RouteMethodDeclaration<BoundAliases, ExpectedParams, Data>>): void

Defines a handler for incoming PUT requests.

The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.

readMethodRoutes(normalizedMethodVerb: RouterMethod): ParsedRoute<BoundAliases>[]

Returns a collection of route handlers for the given HTTP method.

use(fetcher: Fetcher<any>): void

Combines additional routers and their respective route handlers to this router.

Route handlers are matched in the order of their declaration:

const app = new KeyworkRouter()

app.get('/foo', ({request}) => {
  return new Response('This handler got here first!')
})

app.get('/foo', ({request}) => {
  return new Response('This handler won't be called!')
})

However, if you want another router to act as middleware, Call use before defining your route handlers:

const authenticationRouter = new KeyworkRouter()

authenticationRouter.all('*', ({request, next}) => {
  if (!hasAuthCookie(request)) {
    return new KeyworkResourceError(401, "You need to be signed in to do that!")
  }

  // Pass the request along to the next matching route handler.
  return next()
})

const app = new KeyworkRouter()

app.use('/', authenticationRouter)

app.get('/user/profile', ({request}) => {
  return new Response("Some user only content.")
})
use(mountURLPattern: URLPatternLike | string, fetcher: Fetcher<any>): void

Static Properties

readonly
[kObjectName]