1
votes

I am just starting using Vapor 4, and I created a POC to test how to save a Model into a local mySQL database.

Here is the code I am using for the controller that is supposed to save the model to the database.

public class ProductController {
static func create(req: Request) throws -> HTTPStatus {
    do {
        let input = try req.content.decode(Product.self)
        let product = Product(name: input.name, imageUrl: input.imageUrl, priceAmount: input.priceAmount, priceCurrencyCode: input.priceCurrencyCode, category: input.category)
        let _ = input.create(on: req.db).map {
            print("Product saved")
        }
        return HTTPStatus.ok
    } catch {
        return HTTPStatus.badRequest
    }
}

For some reason, "Product saved" never gets printed, so the closure is never called. When I check in the database, the table products is always empty.

Thank you in advance for your help!

Karim

1

1 Answers

3
votes

Try saving the product instead of the input:

return product.create(on: req.db).map { print("Product saved") }
       .transform(to: .ok)