diff --git a/src/orm/base_model/index.ts b/src/orm/base_model/index.ts index 6244fe5c..beb472bc 100644 --- a/src/orm/base_model/index.ts +++ b/src/orm/base_model/index.ts @@ -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 diff --git a/src/types/model.ts b/src/types/model.ts index db2d9459..e178a945 100644 --- a/src/types/model.ts +++ b/src/types/model.ts @@ -618,6 +618,8 @@ export interface LucidRow { fill(value: Partial>, allowExtraProperties?: boolean): this merge(value: Partial>, allowExtraProperties?: boolean): this + isDirty(fields?: keyof ModelAttributes | (keyof ModelAttributes)[]): boolean + /** * Enable force update even when no attributes * are dirty diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 6082709e..630a10a2 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -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) => {