I have a database table called foos
which has two fields, id
and protobuf_data
.
return database.schema("foos")
.id()
.field("protobuf_data", .data, .required)
.create()
The protobuf_data
contains the serialized bytes from a protobuf struct, called Bar
. I have defined the Foo
model class like so:
final class Foo: Model {
static let schema = "foos"
@ID(key: .id)
var id: UUID?
// Holds the serialized bytes for the Bar protobuf
@Field(key: "protobuf_data")
var protobufData: Data
// Deserialized instance from the bytes stored in protobufData
var bar: Bar
}
I am using a custom ModelMiddleware
to serialize the Bar instance and assign the bytes to protobufData
. My question is how can I hook into when a model is read from the database so that I can deserialize the bytes and assign the Bar instance to the my variable?
Note: I am aware of being able to store arbitrary dictionaries to do something similar. However, I would like the serialized format to be protobuf.
Any help or pointers would be greatly appreciated.