Last active
March 7, 2018 20:54
-
-
Save vzsg/fd3d2ac39174d472f036db06a1d8472c to your computer and use it in GitHub Desktop.
Simple extension to use Codable JSON with Vapor 2
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
import Foundation | |
struct MagicTestRequest: Codable { | |
let tokens: [String] | |
} | |
struct MagicTestResponse: Codable { | |
let count: Int | |
} |
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
import Foundation | |
import HTTP | |
extension Encodable { | |
func makeResponse(using encoder: JSONEncoder = JSONEncoder(), | |
status: Status = .ok, | |
contentType: String = "application/json", | |
extraHeaders: [HeaderKey: String] = [:]) throws -> Response { | |
let response = Response(status: status) | |
response.headers = extraHeaders | |
response.headers[.contentType] = contentType | |
let data = try encoder.encode(self) | |
response.body = Body.data(data.makeBytes()) | |
return response | |
} | |
} |
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
import Foundation | |
import HTTP | |
extension HTTP.Message { | |
func decodeJSON<T: Decodable>(using decoder: JSONDecoder = JSONDecoder()) throws -> T { | |
return try decoder.decode(T.self, from: Data(bytes: body.bytes ?? [])) | |
} | |
} |
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
import Vapor | |
extension Droplet { | |
func setupRoutes() throws { | |
post("magic") { req in | |
guard let test: MagicTestRequest = try? req.decodeJSON() else { | |
throw Abort.badRequest | |
} | |
return MagicTestResponse(count: test.tokens.count).makeResponse() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment