Have ideas to improve npm?Join in the discussion! »

    @p-j/eapi-util-fetcheventhandler
    TypeScript icon, indicating that this package has built-in type declarations

    1.1.0 • Public • Published

    @p-j/eapi-util-fetcheventhandler

    This package provide a Fetch Event Handler factory that can be used in a multi-router setup.

    It's especially useful if you combine originless routes with traditional routes on the same project

    It also facilitate the application of "global" middlwares to all your routes.

    Installation

    • From the NPM registry
    npm install @p-j/eapi-util-fetcheventhandler
    # or
    yarn add @p-j/eapi-util-fetcheventhandler

    Usage

    import { fetchEventHandler } from '@p-j/eapi-util-fetcheventhandler'
    import { withErrorHandler } from '@p-j/eapi-middleware-errorhandler'
    
    const requestHandler: RequestHandler = (context) => new Response('Hello World')
    const matcher: RouteMatcher = (event) => { handler: requestHandler, param: {} }
    
    const eventHandler = fetchEventHandler({
      matcher,
      originless: true,
      middlewares: [withErrorHandler()]
    })
    
    addEventListener('fetch', (event) => event.respondWith(fetchEventHandler(event)))

    Example with tiny-request-router

    import { fetchEventHandler } from '@p-j/eapi-util-fetcheventhandler'
    import { withErrorHandler } from '@p-j/eapi-middleware-errorhandler'
    
    const requestHandler: RequestHandler = (context: RequestContext) => new Response('Hello World')
    
    export const router = new Router()
    router.all('/', requestHandler)
    
    const matcher: RouteMatcher = (event: FetchEvent) => {
      const { pathname } = new URL(event.request.url)
      return router.match(event.request.method as Method, pathname)
    }
    
    export const fetchEventHandler = eventHandlerFactory({
      matcher,
      originless: true,
      middlewares: [withErrorHandler()],
    })
    
    addEventListener('fetch', (event) => event.respondWith(fetchEventHandler(event)))

    Install

    npm i @p-j/eapi-util-fetcheventhandler

    DownloadsWeekly Downloads

    4

    Version

    1.1.0

    License

    MIT

    Unpacked Size

    20 kB

    Total Files

    13

    Last publish

    Collaborators

    • avatar