Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 7 additions & 1 deletion src/orm/base_model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1348,9 +1348,15 @@ class BaseModelImpl implements LucidRow {
const dirty = Object.keys(this.$attributes).reduce((result: any, key) => {
const value = this.$attributes[key]
const originalValue = this.$original[key]

const Model = this.constructor as LucidModel
const column = Model.$getColumn(key)

let isEqual = true

if (isObject(value) && 'isDirty' in value) {
if (column?.equals) {
isEqual = column.equals(originalValue, value)
} else if (isObject(value) && 'isDirty' in value) {
isEqual = !value.isDirty
} else {
isEqual = compareValues(originalValue, value)
Expand Down
5 changes: 5 additions & 0 deletions src/types/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,11 @@ export type ColumnOptions = {
* Invoked when row is fetched from the database
*/
consume?: (value: any, attribute: string, model: LucidRow) => any

/**
* Invoked to compare to values for equality when tracking dirty attributes
*/
equals?: (a: any, b: any) => boolean
}

/**
Expand Down
30 changes: 30 additions & 0 deletions test/orm/base_model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,36 @@ test.group('Base Model | dirty', (group) => {
user.location.isDirty = true
assert.deepEqual(user.$dirty, { location: { state: 'goa', country: 'India', isDirty: true } })
})

test('compute diff for properties using equals column option', async ({ fs, assert }) => {
const app = new AppFactory().create(fs.baseUrl, () => {})
await app.init()
const adapter = new FakeAdapter()

const BaseModel = getBaseModel(adapter)

class User extends BaseModel {
@column()
declare username: string

@column()
declare age: number

@column({
equals: (a: Set<string>, b: Set<string>) =>
a.size === b.size && Array.from(a).every((item) => b.has(item)),
})
colors: Set<string> = new Set()
}
User.$adapter = adapter

const user = new User()
user.username = 'virk'
user.colors = new Set(['red', 'green', 'blue'])

assert.isTrue(user.$isDirty)
assert.isTrue(!!user.$dirty.colors)
})
})

test.group('Base Model | persist', (group) => {
Expand Down