Skip to content

Instantly share code, notes, and snippets.

@vzsg
Last active March 7, 2018 20:54
Show Gist options
  • Save vzsg/fd3d2ac39174d472f036db06a1d8472c to your computer and use it in GitHub Desktop.
Save vzsg/fd3d2ac39174d472f036db06a1d8472c to your computer and use it in GitHub Desktop.
Simple extension to use Codable JSON with Vapor 2
import Foundation
struct MagicTestRequest: Codable {
let tokens: [String]
}
struct MagicTestResponse: Codable {
let count: Int
}
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
}
}
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 ?? []))
}
}
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