Skip to content

Commit

Permalink
feat: add isDirty method (#1068)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamcikado authored Dec 4, 2024
1 parent 4a2adcd commit 151f862
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/orm/base_model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1784,6 +1784,19 @@ class BaseModelImpl implements LucidRow {
return this
}

/**
* Returns whether any of the fields have been modified
*/
isDirty(fields?: any): boolean {
const keys = Array.isArray(fields) ? fields : fields ? [fields] : []

if (keys.length === 0) {
return this.$isDirty
}

return keys.some((key) => key in this.$dirty)
}

/**
* Enable force update even when no attributes
* are dirty
Expand Down
2 changes: 2 additions & 0 deletions src/types/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,8 @@ export interface LucidRow {
fill(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this
merge(value: Partial<ModelAttributes<this>>, allowExtraProperties?: boolean): this

isDirty(fields?: keyof ModelAttributes<this> | (keyof ModelAttributes<this>)[]): boolean

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

test('isDirty returns whether field is dirty', async ({ fs, assert }) => {
const app = new AppFactory().create(fs.baseUrl, () => {})
await app.init()
const db = getDb()
const adapter = ormAdapter(db)

const BaseModel = getBaseModel(adapter)

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

@column()
declare email: string
}

const user = new User()

assert.isFalse(user.isDirty())
assert.isFalse(user.isDirty('username'))

user.username = 'virk'

assert.isTrue(user.isDirty())
assert.isTrue(user.isDirty('username'))
assert.isFalse(user.isDirty('email'))
assert.isTrue(user.isDirty(['username', 'email']))
})
})

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

0 comments on commit 151f862

Please sign in to comment.