Skip to content

Instantly share code, notes, and snippets.

@MihaelIsaev
Created April 28, 2018 15:44
Show Gist options
  • Save MihaelIsaev/221272100cd38300822e6298421254ad to your computer and use it in GitHub Desktop.
Save MihaelIsaev/221272100cd38300822e6298421254ad to your computer and use it in GitHub Desktop.
Request+Promise extension for Vapor 3. May be handy if you often create promises in your controllers
import Foundation
import Vapor
extension Request {
func promise<T>(_ asyncCode: @escaping (() throws ->(T))) -> Future<T> where T: ResponseEncodable {
let promise = eventLoop.newPromise(T.self)
DispatchQueue.global().async {
do {
promise.succeed(result: try asyncCode())
} catch {
promise.fail(error: error)
}
}
return promise.futureResult
}
}
//How to use
final class LoginController {
struct LoginResponse: Codable, Content {
var token: String
}
func login(_ req: Request) throws -> Future<LoginResponse> {
struct Content: Codable {
var email: String
var password: String
}
return req.promise { () -> (LoginResponse) in
let requestContent = try req.content.decode(Content.self).wait()
let email = requestContent.email.lowercased()
if !email.doesEmailValid() {
throw Abort(.badRequest, reason: "Invalid email")
}
let user = try User.get(on: req, email: email, password: requestContent.password).wait()
let session = try Session(user: user)//create some session
return LoginResponse(token: session.id)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment