Fatal error when encoding a Model with an non-initialised OptionalParent relation
Closed this issue · 1 comments
tarag commented
If a Model contains an OptionalParent relation that is not initialised to nil in the constructor, it will crash with a fatal error when encoding the model after creation of a new instance.
Fatal error: Cannot access field before it is initialized or fetched: todo_id: file .../fluent-kit/Sources/FluentKit/Properties/Field.swift, line 21
Example based on Vapor 4 template:
Model
final class TodoGroup: Model, Content {
static let schema = "todo_groups"
@ID(key: .id)
var id: UUID?
@Field(key: "title")
var title: String
init() { }
@OptionalParent(key: "todo_id")
public var todo: Todo?
}
Controller method that crashes upon encoding the response:
func create(req: Request) throws -> EventLoopFuture<TodoGroup> {
let group = TodoGroup()
group.title = "My New Todo Group"
return group.save(on: req.db).map { group }
}
Of course the workaround to initialise all relations in the constructor is simple but the consequence if it is forgotten seems severe.
vapor: 4.0.0-rc.3.12
fluent-kit: 1.0.0-rc.1.13
tanner0101 commented
This has been fixed in #270. @OptionalParent
will now return nil
when it is uninitialized.