I'm trying to log all the inbound requests into my database. To do so I've created a Middleware where I fire an event with the data and then a Listener that processes the data and saves it in the db.
I'm able to log all the request information but I'm unable to log the response ones.
This is my middleware:
'use strict'
/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */
const Event = use('Event')
class InboundRequestLogger {
/**
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {Function} next
*/
async handle({request, response}, next) {
Event.fire('new::inboundRequest', {
'method': request.method(),
'url': request.originalUrl(),
'ip': request.ip(),
'headers': request.headers(),
'body': request.all(),
'is_ajax': request.ajax()
})
// call next to advance the request
await next()
}
}
module.exports = InboundRequestLogger
The problem is that I don't know how to fire next()
and then check the response (for example the status code).
I've tried doing like this:
class MyMiddleware {
async handle (ctx, next) {
await next()
ctx.response.response.on('finish', () => {
console.log(ctx.response.response.statusCode)
})
}
}
But nothing happens after the await next()
How can I get the response stuff inside this middleware?
Adonis version: 4.1
the end event handler should be place before calling next
ctx.response.response.on('finish', () => {
console.log(ctx.response.response.statusCode)
})
await next()