Skip to content

Instantly share code, notes, and snippets.

@vzsg
Last active April 24, 2019 14:09
Show Gist options
  • Save vzsg/27a6473ff2fae6f91bdd2f6a25eda3e0 to your computer and use it in GitHub Desktop.
Save vzsg/27a6473ff2fae6f91bdd2f6a25eda3e0 to your computer and use it in GitHub Desktop.
Using IkigaJSON instead of Foundation in Vapor 3
import Vapor
import IkigaJSON
extension IkigaJSONDecoder: DataDecoder {
public func decode<D>(_ decodable: D.Type, from data: LosslessDataConvertible) throws -> D where D : Decodable {
return try self.decode(decodable, from: data.convertToData())
}
}
extension IkigaJSONEncoder: DataEncoder {
}
extension IkigaJSONDecoder: HTTPMessageDecoder {
/// See `HTTPMessageDecoder`
public func decode<D, M>(_ decodable: D.Type, from message: M, maxSize: Int, on worker: Worker) throws -> EventLoopFuture<D>
where D: Decodable, M: HTTPMessage
{
guard message.contentType == .json else {
throw HTTPError(identifier: "contentType", reason: "HTTP message did not have JSON-compatible content-type.")
}
return message.body.consumeData(max: maxSize, on: worker).map(to: D.self) { data in
return try self.decode(D.self, from: data)
}
}
}
extension IkigaJSONEncoder: HTTPMessageEncoder {
/// See `HTTPMessageEncoder`
public func encode<E, M>(_ encodable: E, to message: inout M, on worker: Worker) throws
where E: Encodable, M: HTTPMessage
{
message.contentType = .json
message.body = try HTTPBody(data: encode(encodable))
}
}
import Vapor
import IkigaJSON
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
// ... other configuration omitted for brevity ...
let content: ContentConfig = {
var content = ContentConfig.default()
var decoderSettings = JSONDecoderSettings()
var encoderSettings = JSONEncoderSettings()
decoderSettings.dataDecodingStrategy = .base64
encoderSettings.dataEncodingStrategy = .base64
encoderSettings.encodeNilAsNull = true
if #available(OSX 10.12, *) {
decoderSettings.dateDecodingStrategy = .iso8601
encoderSettings.dateEncodingStrategy = .iso8601
} else {
// never actually hit on Linux or modern macOS
}
let decoder = IkigaJSONDecoder(settings: decoderSettings)
var encoder = IkigaJSONEncoder()
encoder.settings = encoderSettings
content.use(httpDecoder: decoder, for: .json)
content.use(httpEncoder: encoder, for: .json)
return content
}()
services.register(content)
// ...
}
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "VaporApp",
dependencies: [
// ...other dependencies omitted...
.package(url: "https://github.com/Ikiga/IkigaJSON.git", from: "1.1.0"),
],
targets: [
.target(name: "App", dependencies: [...other dependencies..., "IkigaJSON"]),
.target(name: "Run", dependencies: ["App"]),
]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment