Last active
July 22, 2018 20:32
-
-
Save MihaelIsaev/c2531614385716b7b25d9af78f0eb1c3 to your computer and use it in GitHub Desktop.
Attempt to handle routes with [AnyResponse] for Vapor3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Router { | |
@discardableResult | |
func get(_ path: PathComponentsRepresentable..., use closure: @escaping (Request) throws -> [AnyResponse]) -> Route<Responder> | |
{ | |
return _on(.GET, at: path.convertToPathComponents(), use: closure) | |
} | |
@discardableResult | |
func post(_ path: PathComponentsRepresentable..., use closure: @escaping (Request) throws -> [AnyResponse]) -> Route<Responder> | |
{ | |
return _on(.POST, at: path.convertToPathComponents(), use: closure) | |
} | |
@discardableResult | |
func patch(_ path: PathComponentsRepresentable..., use closure: @escaping (Request) throws -> [AnyResponse]) -> Route<Responder> | |
{ | |
return _on(.PATCH, at: path.convertToPathComponents(), use: closure) | |
} | |
@discardableResult | |
func put(_ path: PathComponentsRepresentable..., use closure: @escaping (Request) throws -> [AnyResponse]) -> Route<Responder> | |
{ | |
return _on(.PUT, at: path.convertToPathComponents(), use: closure) | |
} | |
@discardableResult | |
func delete(_ path: PathComponentsRepresentable..., use closure: @escaping (Request) throws -> [AnyResponse]) -> Route<Responder> | |
{ | |
return _on(.DELETE, at: path.convertToPathComponents(), use: closure) | |
} | |
@discardableResult | |
private func _on(_ method: HTTPMethod, at path: [PathComponent], use closure: @escaping (Request) throws -> [AnyResponse]) -> Route<Responder> | |
{ | |
let responder = BasicResponder { data in | |
return try closure(data).map { try $0.encode(for: data) }.flatten(on: data).flatMap { responses in | |
let contents = try responses.map { $0.http.body.data } | |
.compactMap { $0 } | |
.map { try JSONSerialization.jsonObject(with: $0, options: .allowFragments) } | |
let jsonData = try JSONSerialization.data(withJSONObject: contents, options: JSONSerialization.WritingOptions(rawValue: 0)) | |
guard let string = String(data: jsonData, encoding: .utf8) else { throw Abort(.internalServerError, reason: "Unable to decode AnyResponse array") } | |
return try string.encode(for: data) //it should return a json string with an array of response objects | |
} | |
} | |
let route = Route<Responder>(path: [.constant(method.string)] + path, output: responder) | |
register(route: route) | |
return route | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment