Scala - Akka Http - Write a custom directive to add the query params to the form fields of the request

40 Views Asked by At

I want to write a custom directive which adds the query params of the request to its form fields map.

What I have come up till now is something like this

def extractQueryProxyRequestContext: Directive0 = {
 extract { ctx =>

  val queryParams = ctx.request.uri.query().toMap
  val formData = ctx.request.entity.asInstanceOf[FormData]
  val updatedFields = formData.fields ++ queryParams
 }
}

Obviously, this doesn't work, as this just combines them but not pass the updated fields down the request.

2

There are 2 best solutions below

0
Gaël J On

You probably want to use mapRequest or mapRequestContext directives rather than extract if your goal is to modify the initial request.

0
gulgulu On

As suggested by @Gaël J, I used mapRequest to do this. Below is what I followed.

    mapRequest { req =>
  Await.result(req.entity.toStrict(3.seconds)
    .flatMap(Unmarshal.apply(_).to[StrictForm])
    .fast
    .flatMap { form =>
      val fields = form.fields.collect {
        case (name, field) if name.nonEmpty =>
          Unmarshal(field).to[String].map(fieldString => (name, fieldString))
      }
      Future.sequence(fields)
    }
    .map(_.toMap)
    .map { formFields =>
      val queryParams     = req.uri.query().toMap
      val updatedFields   = formFields ++ queryParams
      val updatedFormData = FormData(updatedFields)
      req.withEntity(updatedFormData.toEntity)
    }, 3.seconds)
}