Hi there! Are you looking for the official Deno documentation? Try docs.deno.com for all your Deno learning needs.

createMiddleware

import { createMiddleware } from "https://raw.githubusercontent.com/worker-tools/shed/master/index.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 }
function createMiddleware<Etx extends Rec>(_defaultExt: Callable<Etx>, middlewareFn: <Ctx extends Context>(ax: Awaitable<Ctx>) => Awaitable<Ctx & Etx>);
§
createMiddleware<Etx extends Rec>(_defaultExt: Callable<Etx>, middlewareFn: <Ctx extends Context>(ax: Awaitable<Ctx>) => Awaitable<Ctx & Etx>)
[src]

§Type Parameters

§
Etx extends Rec
[src]

§Parameters

§
_defaultExt: Callable<Etx>
[src]

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>
[src]

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