Skip to content

Instantly share code, notes, and snippets.

@jordanebelanger
Last active January 21, 2021 15:44
Show Gist options
  • Save jordanebelanger/17aedc8ad5f908d4b501785a2809492e to your computer and use it in GitHub Desktop.
Save jordanebelanger/17aedc8ad5f908d4b501785a2809492e to your computer and use it in GitHub Desktop.
Manually encode and decode a codable type to and from a bytebuffer for redis usage
import Vapor
import RedisKit
struct MySession {
let token: RedisKey
let email: String
let userId: Int64
let isAdmin: Bool
let ipAddress: String?
func encode(into buffer: inout ByteBuffer) {
buffer.writeInteger(UInt16(email.count), as: UInt16.self)
buffer.writeString(email)
buffer.writeInteger(userId, as: Int64.self)
buffer.writeInteger(isAdmin ? 1 : 0, as: UInt8.self)
if let ip = ipAddress {
buffer.writeInteger(1, as: UInt8.self)
buffer.writeString(ip)
} else {
buffer.writeInteger(0, as: UInt8.self)
}
}
static func decode(from buffer: inout ByteBuffer, token: String) -> MySession? {
guard
let emailLength = buffer.readInteger(as: UInt16.self),
let email = buffer.readString(length: Int(emailLength)),
let userId = buffer.readInteger(as: Int64.self),
let isAdmin = buffer.readInteger(as: UInt8.self),
let hasIp = buffer.readInteger(as: UInt8.self)
else { return nil }
let ipAddress = hasIp == 1 ? buffer.readString(length: buffer.readableBytes) : nil
return MySession(
token: RedisKey(token),
email: email,
userId: userId,
isAdmin: isAdmin == 1 ? true : false,
ipAddress: ipAddress
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment