Skip to main content
Module

x/workers_middleware/context.ts>createMiddleware

Placeholder for Worker-based middleware solution
Latest
function createMiddleware
import { createMiddleware } from "https://deno.land/x/workers_middleware@v0.1.0-pre.36/context.ts";

A helper function to create user-defined middleware.

Its main purpose is to allow developers to create correctly typed middleware without dealing with generics. This is achieved via the _defaultExt parameter, which is used to infer the types of the extension added to the context. As the _ prefix implies, it is not actually used. The purpose of the default extension object is solely to tell the type checker which additional keys to expect on the context object after this middleware is applied. The job of adding (default) values to the context belongs to the middleware function.

Here are some example usages. All are valid in JavaScript and TypeScript:

const fn = createMiddleware({}, _ => _)
const gn = createMiddleware({}, async ax => ({ ...await ax }))
const hn = createMiddleware({ foo: '' }, async ax => ({ ...await ax, foo: 'star' }))
const jn = createMiddleware({ bar: '' }, async ax => { 
  const x = await ax;
  x.effects.push(resp => {
    resp.headers.set('x-middleware', 'jn')
  })
  return { ...x, bar: 'star' }
})
const myMW = combine(fn, hn, jn, gn) 
//=> Context & { foo: string } & { bar: string }

Type Parameters

Etx extends Rec

Parameters

_defaultExt: Callable<Etx>

The default extension to the current context. Can also be a function that returns the extension object, to avoid unnecessary memory allocation.

middlewareFn: <Ctx extends Context>(ax: Awaitable<Ctx>) => Awaitable<Ctx & Etx>

A middleware functions: Adds the keys listed in defaultExt to the context