Skip to content

Commit

Permalink
fix wildcard rules are not reusable (#1459)
Browse files Browse the repository at this point in the history
  • Loading branch information
tbrockmeyer-a committed Oct 7, 2022
1 parent 37b70f2 commit 592fa39
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/graphql-shield/src/generator.ts
Expand Up @@ -139,10 +139,10 @@ function applyRuleToType(

/* Extract default type wildcard if any and remove it for validation */
const defaultTypeRule = rules['*']
delete rules['*']
const {'*': _, ...rulesWithoutWildcard} = rules;
/* Validation */

const fieldErrors = Object.keys(rules)
const fieldErrors = Object.keys(rulesWithoutWildcard)
.filter((type) => !Object.prototype.hasOwnProperty.call(fieldMap, type))
.map((field) => `${type.name}.${field}`)
.join(', ')
Expand Down
85 changes: 85 additions & 0 deletions packages/graphql-shield/tests/generator.test.ts
Expand Up @@ -268,4 +268,89 @@ describe('generates correct middleware', () => {
expect(defaultQueryMock).toBeCalledTimes(1)
expect(defaultTypeMock).toBeCalledTimes(2)
})

test('correctly allows multiple uses of the same wildcard rule', async () => {
/* Schema */

const typeDefs = `
type Query {
a: String
b: String
type: Type
}
type Type {
field1: String
field2: String
}
`

const resolvers = {
Query: {
a: () => 'a',
b: () => 'b',
type: () => ({
field1: 'field1',
field2: 'field2',
}),
},
}

const schema = makeExecutableSchema({ typeDefs, resolvers })

/* Permissions */

const allowMock = jest.fn().mockResolvedValue(true)
const defaultQueryMock = jest.fn().mockResolvedValue(true)
const defaultTypeMock = jest.fn().mockResolvedValue(true)

const permissions = shield({
Query: {
a: rule({ cache: 'no_cache' })(allowMock),
type: rule({ cache: 'no_cache' })(jest.fn().mockResolvedValue(true)),
'*': rule({ cache: 'no_cache' })(defaultQueryMock),
},
Type: {
'*': rule({ cache: 'no_cache' })(defaultTypeMock),
},
})

/* First usage */
applyMiddleware(schema, permissions)

/* Second usage */
const schemaWithPermissions = applyMiddleware(schema, permissions)

/* Execution */
const query = `
query {
a
b
type {
field1
field2
}
}
`

const res = await graphql({
schema: schemaWithPermissions,
source: query,
})

/* Tests */

expect(res).toEqual({
data: {
a: 'a',
b: 'b',
type: {
field1: 'field1',
field2: 'field2',
},
},
})
expect(allowMock).toBeCalledTimes(1)
expect(defaultQueryMock).toBeCalledTimes(1)
expect(defaultTypeMock).toBeCalledTimes(2)
})
})

0 comments on commit 592fa39

Please sign in to comment.