Skip to content

Commit

Permalink
feat(model): add support for pre-defining timestamp values
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Dec 21, 2018
1 parent 5aa6174 commit f8b5809
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Lucid/Model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ class Model extends BaseModel {
*/
_setUpdatedAt (values, onInsert) {
const updatedAtColumn = this.constructor.updatedAtColumn
if (updatedAtColumn && ((onInsert && !values[updatedAtColumn]) || !onInsert)) {
if (updatedAtColumn && !this.dirty[updatedAtColumn]) {
values[updatedAtColumn] = this._getSetterValue(updatedAtColumn, new Date())
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/Lucid/QueryBuilder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,16 @@ class QueryBuilder {

const valuesCopy = _.clone(valuesOrModelInstance)
const fakeModel = new this.Model()

/**
* Here we fill attributes on the model, so that the logic to
* find if `updated_at` should be set or not can be
* evaluated by the model instance.
*
* For this model instance relies on `dirty` values.
*/
fakeModel.fill(valuesCopy)

fakeModel._setUpdatedAt(valuesCopy)
fakeModel._formatDateFields(valuesCopy)

Expand Down
40 changes: 40 additions & 0 deletions test/unit/lucid.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2028,4 +2028,44 @@ test.group('Model', (group) => {

assert.equal(userQuery.sql, helpers.formatQuery('select * from "users" where (exists (select * from "profiles" where "users"."id" = "profiles"."user_id")) limit ?'))
})

test('do not set created_at when explicitly set in values', async (assert) => {
class User extends Model {
}

User._bootIfNotBooted()
const createdAt = moment().subtract('1', 'day').format('YYYY-MM-DD HH:mm:ss')

const user = await User.create({ username: 'virk', created_at: createdAt })
await user.reload()

assert.equal(user.created_at, createdAt)
})

test('do not set updated_at when explicitly set in values', async (assert) => {
class User extends Model {
}

User._bootIfNotBooted()
const updatedAt = moment().subtract('1', 'day').format('YYYY-MM-DD HH:mm:ss')

const user = await User.create({ username: 'virk', updated_at: updatedAt })
await user.reload()

assert.equal(user.updated_at, updatedAt)
})

test('do not set updated_at when calling update on query builder', async (assert) => {
class User extends Model {
}

User._bootIfNotBooted()
const updatedAt = moment().subtract('1', 'day').format('YYYY-MM-DD HH:mm:ss')

const user = await User.create({ username: 'virk' })
await User.query().where('username', 'virk').update({ updated_at: updatedAt })
await user.reload()

assert.equal(user.updated_at, updatedAt)
})
})

0 comments on commit f8b5809

Please sign in to comment.