vapor / async-kit

Sugary extensions for the SwiftNIO library
MIT License
71 stars 25 forks source link

[Proposal] Future.nonExistant(or:) #13

Closed MrLotU closed 5 years ago

MrLotU commented 5 years ago

In Core there is an extension to Future<OptionalType> adding an unwrap(or:) method that either returns the value if it's not nil or throws the error provided to the function.

This is really useful, but there is no method to do this the other way around. For example, if you're working with a database where a certain key is unique you might not want to rely on the datbase to error, but catch it yourself beforehand with some code like this:

User.query(on: req).filter(\.email, .ilike, providedEmail).first().map { optionalUser in
    guard optionalUser == nil else {
        throw Abort(.badRequest, "user with this email already exists")
    }
    // Continue ...
}

Proposal

Add a nonExistant(or:) function to Future<OptionalType> to allow for flows like this:

User.query(on: req)
    .filter(\.email, .ilike, providedEmail)
    .first()
    .nonExistant(or: Abort(.badRequest, "user with this email already exists"))
    .map {
        // Continue ...
    }
MrLotU commented 5 years ago

In this case nonExistant(or:) would return Future<Void> I'd say, but open to input :D

MrLotU commented 5 years ago

Closing in favour of #27