Timestamp Fields

Episode #364 | 4 minutes | published on November 21, 2018 | Uses fluent-postgresql-1.0.0, Vapor-3.0.8
Subscribers Only
If you want to track when records are created and modified, you can add some fields to your model and Fluent will automatically manage them for you. You just have to take care to define your TimestampKey properties carefully so they match what Fluent expects.

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!

blog comments powered by Disqus