Skip to content

Instantly share code, notes, and snippets.

@thecoolwinter
Created June 23, 2021 23:02
Show Gist options
  • Save thecoolwinter/e6f8d45852acb2fe45f7fb79a0f8dc23 to your computer and use it in GitHub Desktop.
Save thecoolwinter/e6f8d45852acb2fe45f7fb79a0f8dc23 to your computer and use it in GitHub Desktop.
A small extension for easily adding timestamps to models with one line in a migration. You can customize the fieldnames as well. By default adds `createdAt`, `updatedAt` and `deletedAt`.
import Fluent
extension SchemaBuilder {
enum TimestampTypes: Equatable {
case createdAt(_ fieldName: String = "createdAt")
case updatedAt(_ fieldName: String = "updatedAt")
case deletedAt(_ fieldName: String = "deletedAt")
}
func addTimestamps(_ types: [TimestampTypes] = [.createdAt(), .updatedAt(), .deletedAt()]) -> SchemaBuilder {
var value = self
for type in types {
switch type {
case .createdAt(let fieldName):
value = value.field(fieldName, .datetime)
case .updatedAt(let fieldName):
value = value.field(fieldName, .datetime)
case .deletedAt(let fieldName):
value = value.field(fieldName, .datetime)
}
}
return value
}
}
@thecoolwinter
Copy link
Author

Use like so:

struct Migration: Fluent.Migration {
        func prepare(on database: Database) -> EventLoopFuture<Void> {
            database.schema(Contact.schema)
                .id()
                .addTimestamps()
                .create()
        }
        
        func revert(on database: Database) -> EventLoopFuture<Void> {
            database.schema(Contact.schema)
                .delete()
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment