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.
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)
}