Search code examples
fluentvapor

request, that save array of models in vapor 3


How can I update an array of models into mysql using transactions? and return Ok response after successful operation


Solution

  • So, I solved my problem without transactions:

    func update(_ req: Request, todos: [CreateTodoRequest]) throws -> Future<HTTPStatus> {
        let user = try req.requireAuthenticated(User.self)
        // 1
        return try todos.map { try Todo(todo: $0, userID: user.requireID()).create(on: req) }
            // 2
            .flatten(on: req)
            // 3
            .transform(to: .ok)
    }
    

    .create(on: req) returns an EventLoopFuture<Todo>. So todos.map will return an array of [EventLoopFuture<Todo>]. The second step is to transform it to EventLoopFuture<[Todo]>. And the third step is to transform it to HttpStatus.ok response