Skip to content

Commit

Permalink
fix: ensure it's possible to chain accessibleBy after another `acce…
Browse files Browse the repository at this point in the history
…ssibleBy` and combine with other `Query` methods
  • Loading branch information
serhiistotskyi committed Nov 4, 2021
1 parent a5f1036 commit 5632c53
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
5 changes: 5 additions & 0 deletions packages/casl-mongoose/spec/accessible_records.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Post, Post>

Expand Down
17 changes: 10 additions & 7 deletions packages/casl-mongoose/src/accessible_records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ function failedQuery(
return query;
}

type GetAccessibleRecords<T extends Document> = <U extends AnyMongoAbility>(
ability: U,
action?: Normalize<Generics<U>['abilities']>[0]
) => QueryWithHelpers<T, T>;

function accessibleBy<T extends AnyMongoAbility>(
this: any,
ability: T,
Expand All @@ -54,9 +49,17 @@ function accessibleBy<T extends AnyMongoAbility>(
return this instanceof mongoose.Query ? this.and([query]) : this.where({ $and: [query] });
}

export interface AccessibleRecordModel<T extends Document, K = {}> extends Model<T, K & {
type GetAccessibleRecords<T extends Document> = <U extends AnyMongoAbility>(
ability: U,
action?: Normalize<Generics<U>['abilities']>[0]
) => QueryWithHelpers<T, T, QueryHelpers<T>>;

type QueryHelpers<T extends Document> = {
accessibleBy: GetAccessibleRecords<T>
}> {
};
export interface AccessibleRecordModel<
T extends Document, K = unknown
> extends Model<T, K & QueryHelpers<T>> {
accessibleBy: GetAccessibleRecords<T>
}

Expand Down

0 comments on commit 5632c53

Please sign in to comment.