Allows to create Model's fields as an enum and then safely use it without hassling with string literals and suffering from fat fingers.
extension User: FieldsProvidingModel {
enum Fields: String, FieldKeyRepresentable {
case username
}
}
final class User: Model, Content {
static let schema = "users"
@ID(key: .id)
var id: UUID?
@Field(key: Fields.username.key)
var username: String?
}
extension User: InitMigratableSchema {
static func prepare(on schemaBuilder: SchemaBuilder) -> EventLoopFuture<Void> {
return schemaBuilder
.id()
.field(Fields.username.key, .string)
.create()
}
}
Easy-breazy stuff for creating initial migrations in three simple steps.
- Make your model conform to InitMigratableSchema protocol, by implementing static prepare(...) method (almost as usual)
extension User: InitMigratableSchema {
static func prepare(on schemaBuilder: SchemaBuilder) -> EventLoopFuture<Void> {
return schemaBuilder
.id()
.field(Fields.username.key, .string)
.create()
}
}
- Add initial migration for the model in your configuration file:
func configureDatabaseInitialMigrations(_ app: Application) {
app.migrations.add(User.createInitialMigration())
}
Short-cut for creating many-to-many relations.
- Define whatever as SiblingRepresentable (enum for example)
extension Todo {
enum Relations {
enum RelatedTags: SiblingRepresentable {
typealias From = Todo
typealias To = Tag
typealias Through = SiblingModel<Todo, Tag, Self>
}
}
}
- Add corresponding property with @Siblings property wrapper
final class User: Model, Content {
static let schema = "users"
@ID(key: .id)
var id: UUID?
@Siblings(through: Relations.RelatedTags.through, from: \.$from, to: \.$to)
var relatedTags: [Tag]
}
- Add initial migration for pivot Fluent model representing the sibling after related models:
private func configureDatabaseInitialMigrations(_ app: Application) {
app.migrations.add(Todo.createInitialMigration())
app.migrations.add(Tag.createInitialMigration())
app.migrations.add(Todo.Relations.RelatedTags.Through.createInitialMigration())
}
- Profit! No need to feel pain from pivot models manual creation any more.