Search code examples
swiftvapor

How to always return an array in Vapor 3 and Fluent (even for single entity requests)


I'd like to have an index controller function that returns an array of entities if no request parameter is set or a single entity if the id parameter is set. However, I'd like to always receive an array, in the latter case it just contains only one element.

Here's my function:

final class AddressController {
    func index(_ req: Request) throws -> Future<[Address]> {
        if let id = try? req.query.get(UUID.self, at: "id") {
            // THIS IS NOT WORKING...
            return Address.find(id, on: req)
        } else {
            return Address.query(on: req).all()
        }
    }
}

Solution

  • final class AddressController {
        func index(_ req: Request) throws -> Future<[Address]> {
            if let id = try? req.query.get(UUID.self, at: "id") {
                return Address.find(id, on: req).map {
                    guard let address = $0 else { return [] }
                    return [address]
                }
            } else {
                return Address.query(on: req).all()
            }
        }
    }