
This video is only available to subscribers. Start a subscription today to get access to this and 472 other videos.
Timestamp Fields
This episode is part of a series: Server-side Swift with Vapor.
1. Getting Started with Vapor 12 min |
2. Vapor Routing 14 min |
3. Leaf Templates 13 min |
4. Nesting Templates and Partials 8 min |
5. Vapor Demo: Tokenizr 21 min |
6. Setting up a Database with Fluent 19 min |
7. Creating, Updating, and Deleting Records with Fluent 19 min |
8. Vapor Futures 20 min |
9. Setting up Vapor with Postgresql 17 min |
10. UUID Primary Keys 13 min |
11. Timestamp Fields 4 min |
12. Refactoring to Protocols 12 min |
13. Parent Child Relationships and Foreign Keys 14 min |
14. Pivot Tables for Many to Many Relationships 14 min |
15. Vapor Controllers 15 min |
16. Decoding Request Parameters 9 min |
Adding the fields
First, we declare some fields on our model:
final class Project : Model {
// ....
var createdAt: Date?
var updatedAt: Date?
// ....
}
Then we update our migration to add these fields (at this point we are still in the early stages of development, so modifying the original migration is okay since we don't mind destroying the database and recreating)
extension Project : Migration {
static func prepare(on connection: Database.Connection) -> Future<Void> {
return PostgreSQLDatabase.create(on: connection) { builder in
//...
builder.field(for: \.createdAt)
builder.field(for: \.updatedAt)
}
}
}
Configuring Fluent to update these fields
For Fluent to automatically update these, we need to specify the key paths our model defines for these dates:
static var createdAtKey: TimestampKey? = \.createdAt
static var updatedAtKey: TimestampKey? = \.updatedAt
Take care to get this definition right, as you won't get a compile error if it doesn't match exactly, it just won't work. If you have all these pieces in place, then saving a new record (or updating an existing one) will properly update these timestamps for you!