Skip to content

Instantly share code, notes, and snippets.

@iljaiwas
Created March 14, 2019 11:11
Show Gist options
  • Save iljaiwas/272a1b771705b46c4f3051d8664cb978 to your computer and use it in GitHub Desktop.
Save iljaiwas/272a1b771705b46c4f3051d8664cb978 to your computer and use it in GitHub Desktop.
Drop-in replacement for Data ivars that gets stored efficiently in MySQL by Vapor 3.
import Foundation
import Vapor
import FluentMySQL
final class BinaryData {
private let data: Data
init(data: Data) {
self.data = data
}
enum CodingKeys: String, CodingKey {
case data
}
}
extension BinaryData: ReflectionDecodable {
static func reflectDecoded() throws -> (BinaryData, BinaryData) {
return (BinaryData(data: Data(bytes: [UInt8(1)])), BinaryData(data: Data(bytes: [UInt8(2)])))
}
static func reflectDecodedIsLeft(_ item: BinaryData) throws -> Bool {
return item.data[0] == UInt8(1)
}
}
extension BinaryData: MySQLDataConvertible {
func convertToMySQLData() -> MySQLData {
return MySQLData(data: data)
}
static func convertFromMySQLData(_ mysqlData: MySQLData) throws -> BinaryData {
return BinaryData(data: mysqlData.data() ?? Data())
}
}
extension BinaryData: Content {
convenience init(from decoder: Decoder) throws {
self.init(data: try decoder.singleValueContainer().decode(Data.self))
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment