Is there a lifecycle hook for reading a Fluent model?

I have a database table called foos which has two fields, id and protobuf_data.

    return database.schema("foos")
      .field("protobuf_data", .data, .required)

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.

There aren't any hooks for that built into Fluent. You could override the decoding properties for the model which would have the same effect (or use a custom property wrapper)

I will give that a try. Thanks for the suggestion.

Terms of Service

Privacy Policy

Cookie Policy