How to edit all coming request


#1

Hi Team,

How to edit/sanitize all incoming request data as global level


#2

Hey @sudhiN! :wave:

You should create a middleware for that.

https://adonisjs.com/docs/4.1/middleware


#3

Yes, I have created a global middleware, but how to update the sanitized data back to request


#4

By mutating the request object.
Here’s an example of a Middleware that converts empty strings to null.

'use strict'

class ConvertEmptyStringsToNull {
  async handle ({ request }, next) {
    if (Object.keys(request.body).length) {
      request.body = Object.assign(
        ...Object.keys(request.body).map(key => ({
          [key]: request.body[key] !== '' ? request.body[key] : null
        }))
      )
    }

    await next()
  }
}

module.exports = ConvertEmptyStringsToNull

#5

Thank you :smiling_face_with_three_hearts: