Middleware
Middleware
Middleware is the path to a handler made programmable. Each step can inspect the event, pass it inward, and act on the response coming back. It is the same chain of responsibility that builds the manifest, now applied to requests, and it is where auth, validation and logging live.
#The pipe model
A middleware receives the event and a next function. Everything before next(event) is the way in; call it to continue toward the handler; everything after is the way out, acting on the response. Return early, without calling next, to short-circuit.
import { Middleware, NextPipe } from '@stone-js/core'
import { IncomingHttpEvent, OutgoingHttpResponse } from '@stone-js/http-core'
@Middleware()
export class Timing {
async handle (event: IncomingHttpEvent, next: NextPipe<IncomingHttpEvent, OutgoingHttpResponse>) {
const started = performance.now()
const response = await next(event) // in: continue toward the handler
response.setHeader('x-time', String(performance.now() - started))
return response // out: act on the way back
}
}import { defineMiddleware } from '@stone-js/core'
export const timing = defineMiddleware(async (event, next) => {
const started = performance.now()
const response = await next(event)
response.setHeader('x-time', String(performance.now() - started))
return response
})Before next(): the way in. After next(): the way out. Skip next(): the request stops here.