Search code examples
iosfuturevapor

Vapor: Post processing on a query result?


Vapor/Future newbie here, who's fighting with the type system.

I'd like to do some processing on query results:

  1. Do query.
  2. Change/save results.
  3. Return changed results.

For example:

func myIndex(_ req: Request) throws -> Future<[Todo]> {
    return Todo.query(on: req)
            .all()
            .flatMap { allToDos in
                allToDos.flatMap { toDo in
                    // change toDoch
                    return toDo.save(on: req).flatMap { $0 }
                }
    }
}

Which results in: enter image description here

So what's the correct pattern for this kind of thing?


Solution

  • Use flatten

    func changeAllTodos(_ req: Request) throws -> Future<HTTPStatus> {
        return Todo.query(on: req).all().flatMap { allToDos in
            return allToDos.map { toDo in
                // change toDoch
                return toDo.save(on: req).transform(to: ())
            }.flatten(on: req).transform(to: .ok)
        }
    }