Skip to content

Commit

Permalink
fix: changes empty result query to be $expr with object, otherwise mo…
Browse files Browse the repository at this point in the history
…ngoose throws error

But mongo works OK with `{ $expr: false }` however official docs says it should be an object
  • Loading branch information
stalniy committed Jul 28, 2023
1 parent 572b0e6 commit 9eae155
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 5 deletions.
4 changes: 2 additions & 2 deletions packages/casl-mongoose/spec/accessibleBy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('accessibleBy', () => {

const query = accessibleBy(ability, 'update').Post

expect(query).toEqual({ $expr: false })
expect(query).toEqual({ $expr: { $eq: [0, 1] } })
})

it('returns `{ $expr: false }` if there is a rule that forbids previous one', () => {
Expand All @@ -27,7 +27,7 @@ describe('accessibleBy', () => {

const query = accessibleBy(ability, 'update').Post

expect(query).toEqual({ $expr: false })
expect(query).toEqual({ $expr: { $eq: [0, 1] } })
})

describe('it behaves like `toMongoQuery` when converting rules', () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/casl-mongoose/src/accessible_records.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { Normalize, AnyMongoAbility, Generics, ForbiddenError } from '@casl/ability';
import { Schema, QueryWithHelpers, Model, Document, HydratedDocument, Query } from 'mongoose';
import { toMongoQuery } from './mongo';
import { EMPTY_RESULT_QUERY, toMongoQuery } from './mongo';

function failedQuery(
ability: AnyMongoAbility,
action: string,
modelName: string,
query: QueryWithHelpers<Document, Document>
) {
query.where({ $expr: false }); // rule that returns empty result set
query.where(EMPTY_RESULT_QUERY);
const anyQuery: any = query;

if (typeof anyQuery.pre === 'function') {
Expand Down
3 changes: 2 additions & 1 deletion packages/casl-mongoose/src/mongo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ export function accessibleBy<T extends AnyMongoAbility>(
}, accessibleByProxyHandlers) as unknown as Record<StringOrKeysOf<RecordTypes>, AbilityQuery>;
}

export const EMPTY_RESULT_QUERY = { $expr: { $eq: [0, 1] } };
const accessibleByProxyHandlers: ProxyHandler<{ _ability: AnyMongoAbility, _action: string }> = {
get(target, subjectType) {
const query = rulesToQuery(target._ability, target._action, subjectType, convertToMongoQuery);
return query === null ? { $expr: false } : query;
return query === null ? EMPTY_RESULT_QUERY : query;
}
};

0 comments on commit 9eae155

Please sign in to comment.