Group Group Group Group Group Group Group Group Group

Handle POST of JSON data - save straight to database

All the examples for Vapor 3 seems to show how to receive JSON POST and create a Codable struct to map the data from the request body too. I’ve been working with that for a while.

Now I need to be able to a simply receive POST requests contain any arbitrary JSON and to be able to save that as a string to a table in a database. This is so that I can receive a range of POST from different Webhooks POSTs and log the raw request before I attempt any post-processing.
Later on I’ll get to processing the JSON - but I am going slowly, one step at a time.

I’ve created a Controller with a .post(use: createHandler) definition and can successful post data to the end-point… then I am stuck.
I also have a model defined to save the data to the database - it simply has and ID, date and rawJSON: String property.

The controller isn’t expected to return any response other than http OK

In the createHandler method I’ve been able to read the content via req.content, but it contains everything (let allContent = req.content)
Guessing that I need to decode it to something…

Any help /pointers welcomed.

Update on progress so far…

in my createHandler method

if let data = req.http.body.data {
    if let rawJSON = String(data: data, encoding .utf8) {
       print(rawJSON)
}

baby steps

Yep that’s the way to do it!