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

feat: add isDirty method #1068

Merged
merged 1 commit into from
Dec 4, 2024
Merged
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
13 changes: 13 additions & 0 deletions src/orm/base_model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1766,6 +1766,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 @@ -613,6 +613,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
Loading