From 5632c53de5dc62c10b19864686c82e87d17b6147 Mon Sep 17 00:00:00 2001 From: Serhii Stotskyi Date: Thu, 4 Nov 2021 17:29:27 +0200 Subject: [PATCH] fix: ensure it's possible to chain `accessibleBy` after another `accessibleBy` and combine with other `Query` methods --- .../spec/accessible_records.spec.ts | 5 +++++ .../casl-mongoose/src/accessible_records.ts | 17 ++++++++++------- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/casl-mongoose/spec/accessible_records.spec.ts b/packages/casl-mongoose/spec/accessible_records.spec.ts index b0ff7264b..4bd64a56c 100644 --- a/packages/casl-mongoose/spec/accessible_records.spec.ts +++ b/packages/casl-mongoose/spec/accessible_records.spec.ts @@ -74,6 +74,11 @@ describe('Accessible Records Plugin', () => { ]) }) + it('allows to chain `accessibleBy` method', () => { + Post.find().accessibleBy(ability).accessibleBy(ability, 'update') + Post.accessibleBy(ability).where({ title: /test/ }).accessibleBy(ability, 'delete') + }) + describe('when ability disallow to perform an action', () => { let query: mongoose.QueryWithHelpers diff --git a/packages/casl-mongoose/src/accessible_records.ts b/packages/casl-mongoose/src/accessible_records.ts index 8ffdb7f07..bb93ca364 100644 --- a/packages/casl-mongoose/src/accessible_records.ts +++ b/packages/casl-mongoose/src/accessible_records.ts @@ -25,11 +25,6 @@ function failedQuery( return query; } -type GetAccessibleRecords = ( - ability: U, - action?: Normalize['abilities']>[0] -) => QueryWithHelpers; - function accessibleBy( this: any, ability: T, @@ -54,9 +49,17 @@ function accessibleBy( return this instanceof mongoose.Query ? this.and([query]) : this.where({ $and: [query] }); } -export interface AccessibleRecordModel extends Model = ( + ability: U, + action?: Normalize['abilities']>[0] +) => QueryWithHelpers>; + +type QueryHelpers = { accessibleBy: GetAccessibleRecords -}> { +}; +export interface AccessibleRecordModel< + T extends Document, K = unknown +> extends Model> { accessibleBy: GetAccessibleRecords }