Reputation: 1430
One of my Vapor app endpoints needs to be able to receive arbitrary JSON and output it to the logs. Once I have the logs, I can go back through and set up Codables structs and do the typical Vapor workflow.
Upvotes: 0
Views: 136
Reputation: 1430
Doing this requires solving two problems that Vapor apps don't normally contend with:
The simplest solution I found gets the body from req.http.body.data
, converts the data to JSON using JSONSerialization.jsonObject(with:options)
, and returns a Future using req.eventLoop.newSucceededFuture
:
router.put("printanyjson") { req -> Future<HTTPStatus> in
if let data = req.http.body.data {
if let json = try? JSONSerialization.jsonObject(with: data, options: []) {
print("\(json)")
}
}
return req.eventLoop.newSucceededFuture(result: .ok)
}
Note #1: This solution does not work if body is streaming. I'd like to see a solution that incorporates this idea.
Note #2: It's also possible to make recursive Codables that can decode any structure, allowing you to stay within the rails of typical Vapor usage. I'd like to see a solution that incorporates this idea.
Upvotes: 0