Route Middleware
Agregar middleware a una sola ruta, ya sea como argumentos antes del handler o a través de la opción middleware.
Pasa middleware antes del handler para agregarlo a una sola ruta:
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get(
'/reports',
async (ctx, next) => {
if (ctx.request.headers.get('authorization') === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
},
() => ({ reports: [] })
)
app.listen()El último argumento siempre es el handler; todo lo anterior es middleware, que corre en el orden en que se escribió. Se puede pasar cualquier cantidad:
import { Arcton } from '@arcton/core'
import type { Middleware } from '@arcton/contracts'
const authenticate: Middleware = async (ctx, next) => {
if (ctx.request.headers.get('authorization') === null) {
return new Response('Unauthorized', { status: 401 })
}
await next()
}
const audit: Middleware = async (ctx, next) => {
await next()
console.log(`audited ${new URL(ctx.request.url).pathname}`)
}
const app = Arcton()
app.delete('/users/:id', authenticate, audit, ctx => ({
deleted: ctx.params.id
}))
app.listen()El middleware de ruta se tipa por su ruta
Un middleware escrito en línea recibe los tipos de parámetro de la ruta:
import { Arcton } from '@arcton/core'
const app = Arcton()
app.get(
'/users/:id',
async (ctx, next) => {
console.log(`looking up user ${ctx.params.id}`)
await next()
},
ctx => ({ id: ctx.params.id })
)
app.listen()Un middleware declarado por separado como Middleware es reusable
entre rutas y ve ctx.params como Record<string, string>.
Con la forma de opciones
Cuando una ruta usa la forma de opciones,
el middleware va en el array middleware:
import { Arcton } from '@arcton/core'
import * as v from 'valibot'
const app = Arcton()
app.post('/users/:id/orders', {
params: v.object({
id: v.pipe(v.string(), v.transform(Number), v.number())
}),
body: v.object({
item: v.string(),
quantity: v.pipe(v.number(), v.integer(), v.minValue(1))
}),
middleware: [
async (ctx, next) => {
console.log(`order for user ${ctx.params.id}: ${ctx.body.item}`)
await next()
}
],
handler: ctx => ({ userId: ctx.params.id, order: ctx.body })
})
app.listen()El middleware de ruta corre después de la validation, así que ve
los valores ya validados y convertidos: ctx.params.id aquí es un
número, y ctx.body está tipado a partir del schema.
Dónde se ubica en la cadena
El middleware de ruta es la capa más interior, la más cercana al handler:
global middleware → validation → route middleware → handlerAsí que un middleware global envuelve a un middleware de ruta, que envuelve al handler. Ver Execution order.
Como el middleware de ruta pertenece a una ruta matcheada, no corre
sobre las respuestas 404 y 405 que genera Arcton.