Skip to content

Commit

Permalink
fix: allow variables inference in GraphQLRequest (#1081)
Browse files Browse the repository at this point in the history
* fix: allow variables inference in GraphQLRequest

I noticed that the return type of a `graphql.query<T, N>...` call is
`GraphQLHandler<GraphQLRequest<any>>` - it's not propagating the
variables generic parameter into the return type.  I assume this wasn't
intentional.

This change annotates the constructor of the `GraphQLHandler` class with
the correct generic parameters, so the return type should now be
`GraphQLHandler<GraphqlRequest<N>>`.

* test(graphql): add variables inference typing test

Co-authored-by: Artem Zakharchenko <kettanaito@gmail.com>
  • Loading branch information
obmarg and kettanaito committed Jan 30, 2022
1 parent ddbc5a7 commit 6e7ec28
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
14 changes: 12 additions & 2 deletions src/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,12 @@ function createScopedGraphQLHandler(
GraphQLContext<Query>
>,
) => {
return new GraphQLHandler(operationType, operationName, url, resolver)
return new GraphQLHandler<GraphQLRequest<Variables>>(
operationType,
operationName,
url,
resolver,
)
}
}

Expand All @@ -50,7 +55,12 @@ function createGraphQLOperationHandler(url: Path) {
GraphQLContext<Query>
>,
) => {
return new GraphQLHandler('all', new RegExp('.*'), url, resolver)
return new GraphQLHandler<GraphQLRequest<Variables>>(
'all',
new RegExp('.*'),
url,
resolver,
)
}
}

Expand Down
26 changes: 25 additions & 1 deletion test/typings/graphql.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { parse } from 'graphql'
import { graphql } from 'msw'
import {
MockedRequest,
GraphQLRequest,
graphql,
GraphQLHandler,
GraphQLVariables,
} from 'msw'

graphql.query<{ key: string }>('', (req, res, ctx) => {
return res(
Expand Down Expand Up @@ -109,3 +115,21 @@ graphql.mutation(createUser, (req, res, ctx) =>
}),
),
)

// GraphQL request variables must be inferrable
// via the variables generic.
function extractVariables<Variables extends GraphQLVariables>(
_handler: GraphQLHandler<GraphQLRequest<Variables>>,
): MockedRequest<GraphQLRequest<Variables>> {
return null as any
}
const handlerWithVariables = graphql.query<{ data: unknown }, { id: string }>(
'GetUser',
() => void 0,
)
const handler = extractVariables(handlerWithVariables)

handler.body.variables.id

// @ts-expect-error Property "foo" is not defined on the variables generic.
handler.body.variables.foo

0 comments on commit 6e7ec28

Please sign in to comment.