Skip to content

Commit

Permalink
fix(mongoose): accessibleBy now doesn't change query type
Browse files Browse the repository at this point in the history
So, it's possible to add it anywhere in query chain:
```js
Post.findById(1).accessibleBy(ability)
// returns the same results as
Post.accessibleBy(ability).findById(1)
```

Fixes #87
  • Loading branch information
stalniy committed Jul 2, 2018
1 parent c8e91b0 commit da7ed74
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
19 changes: 13 additions & 6 deletions packages/casl-mongoose/spec/accessible_records.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,26 @@ describe('Accessible Records Plugin', () => {
expect(ability.rulesFor).to.have.been.called.with.exactly('delete', Post.modelName)
})

it('calls `find` method of the query', () => {
spy.on(Post, 'find')
it('calls `where` method of the query', () => {
spy.on(Post, 'where')
Post.accessibleBy(ability)

expect(Post.find).to.be.called()
expect(Post.where).to.be.called()
})

it('passes query created by `toMongoQuery` in `find` method of the query', () => {
it('passes query created by `toMongoQuery` in `where` method of the query', () => {
const query = toMongoQuery(ability, 'Post')
spy.on(Post, 'find')
spy.on(Post, 'where')
Post.accessibleBy(ability)

expect(Post.find).to.be.called.with.exactly(query)
expect(Post.where).to.be.called.with.exactly(query)
})

it('does not change query return type', () => {
const originalType = Post.findById(1).op
const type = Post.findById(1).accessibleBy(ability).op

expect(type).to.equal(originalType)
})

describe('when ability disallow to perform an action', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/casl-mongoose/src/accessible_records.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function emptyQuery(query) {
function accessibleBy(ability, action) {
const query = toMongoQuery(ability, this.modelName || this.model.modelName, action);

return query === null ? emptyQuery(this.find()) : this.find(query);
return query === null ? emptyQuery(this.where()) : this.where(query);
}

export function accessibleRecordsPlugin(schema) {
Expand Down

0 comments on commit da7ed74

Please sign in to comment.