Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to set custom createdAt/updatedAt on create #520

Merged
merged 6 commits into from
Jun 19, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 22 additions & 9 deletions Sources/Fluent/QueryBuilder/QueryBuilder+Model.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,28 @@ extension QueryBuilder where Result: Model, Result.Database == Database {
/// - returns: A `Future` containing the created `Model`.
public func create(_ model: Result) -> Future<Result> {
Database.queryActionApply(Database.queryActionCreate, to: &query)
var copy: Result
if Result.createdAtKey != nil || Result.updatedAtKey != nil {
// set timestamps
copy = model
let now = Date()
copy.fluentUpdatedAt = now
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No reason to set the model's existing property on the copy, it will already be there. Just check here if fluentUpdatedAt is nil before setting (same for fluentCreatedAt)

copy.fluentCreatedAt = now
} else {
copy = model
var copy = model

let now = Date()

// check if TimestampKey is used for createdAt property
if let createdAt = Result.createdAtKey {
// check if custom createdAt value is specified
if let date = model[keyPath: createdAt] {
copy.fluentCreatedAt = date
} else {
copy.fluentCreatedAt = now
}
}

// check if TimestampKey is used for updatedAt property
if let updatedAt = Result.updatedAtKey {
// check if custom updatedAt value is specified
if let date = model[keyPath: updatedAt] {
copy.fluentUpdatedAt = date
} else {
copy.fluentUpdatedAt = now
}
}

return connection.flatMap { conn in
Expand Down