Episode #364

Timestamp Fields

Series: Server-side Swift with Vapor

4 minutes
Published on November 21, 2018

This video is only available to subscribers. Get access to this video and 582 others.

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!

This episode uses Vapor 3.0.8, Fluent postgresql-1.0.0.