How to extend REST API functionality with middleware
Middleware with the REST API are just the usual Express middleware. You may define a list of middleware to run before a route using the .middleware()
method on a route instance:
import { route } from '@tensei/core'
route('Download invoices')
.post()
.path('users/invoices/downloads')
.middleware([async (request, response, next) => {
if (! request.user.invoices) {
return response.status(401).json({
message: 'You are not authorized to download invoices.'
})
}
next()
}])
.handle((request, response) => request.users.invoices)
You may also define middleware on existing routes. To get an existing route, for example those generated by tensei, you may use the getRoute()
method. A good place to do this would be in the .register()
hook:
import { tensei } from '@tensei/core'
tensei()
.register(({ getRoute }) => {
getRoute('createComments')
?.middleware([...])
})
Since middleware use the underlying express server, you may define middleware directly on the express instance. A good place to do this would be the .register()
hook:
import { tensei } from '@tensei/core'
const pino = require('express-pino-logger')()
tensei()
.register(({ app }) => {
app.use(pino())
})