Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request, that save array of models in vapor 3

Tags:

vapor

fluent

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

like image 276
Argas Avatar asked Sep 30 '18 08:09

Argas


Video Answer


1 Answers

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

like image 80
Argas Avatar answered Oct 11 '22 19:10

Argas