Barry Jones
Barry Jones

Reputation: 1430

How to output any JSON sent to endpoint?

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

Answers (2)

0xTim
0xTim

Reputation: 5620

In your route handler do print("\(req)") and you'll see the data

Upvotes: 2

Barry Jones
Barry Jones

Reputation: 1430

Doing this requires solving two problems that Vapor apps don't normally contend with:

  1. Where to get the HTTP body (and how to decode it)?
  2. How to return a future outside the context of the usual helpers?

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

Related Questions