Skip to content

Instantly share code, notes, and snippets.

@siemensikkema
Created January 22, 2020 08:53
Show Gist options
  • Save siemensikkema/02bfea1d37656135163cf67d88b1389b to your computer and use it in GitHub Desktop.
Save siemensikkema/02bfea1d37656135163cf67d88b1389b to your computer and use it in GitHub Desktop.
func createUser(request: Request) -> EventLoopFuture<HTTPResponseStatus> {
let password: String? = request.content["password"]
let email: String? = request.content["email"]
User.query(on: request.db).filter(\.email == email).count().map {
var validations = NewUser.validations()
validations.add("passwordAgain", as: String, is: .in(["password"])) // we need a .equals validator
if email != nil {
validations.add("email", result: UniqueEmailValidatorResult())
}
return validations
}.flatMapThrowing {
try $0.validate(request).assert()
}.map { .ok } // obviously we need to create the user here as well
}
struct UniqueEmailValidatorResult: ValidatorResult {
public var isFailure: Bool {
true
}
public var successDescription: String? {
nil
}
public var failureDescription: String? {
"email already exists"
}
}
struct NewUser {
let password: String
let passwordAgain: String
let email: String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment