1
- import { DocumentNode , getOperationAST , GraphQLError , OperationDefinitionNode } from 'graphql' ;
1
+ import { DocumentNode , GraphQLError , Kind } from 'graphql' ;
2
2
import { Maybe } from '@envelop/core' ;
3
- import { createGraphQLError } from '@graphql-tools/utils' ;
3
+ import { createGraphQLError , isDocumentNode } from '@graphql-tools/utils' ;
4
4
import type { YogaInitialContext } from '../../types.js' ;
5
5
import type { Plugin } from '../types.js' ;
6
6
7
- export function assertMutationViaGet (
8
- method : string ,
9
- document : Maybe < DocumentNode > ,
10
- operationName ?: string ,
11
- ) {
12
- const operation : OperationDefinitionNode | undefined = document
13
- ? getOperationAST ( document , operationName ) ?? undefined
14
- : undefined ;
7
+ export function assertMutationViaGet ( method : string , document : Maybe < DocumentNode > ) {
8
+ const isMutation =
9
+ document ?. definitions . find ( def => def . kind === Kind . OPERATION_DEFINITION ) ?. operation ===
10
+ 'mutation' ;
15
11
16
- if ( ! operation ) {
17
- throw createGraphQLError ( 'Could not determine what operation to execute.' , {
18
- extensions : {
19
- http : {
20
- status : 400 ,
21
- } ,
22
- } ,
23
- } ) ;
24
- }
25
-
26
- if ( operation . operation === 'mutation' && method === 'GET' ) {
12
+ if ( isMutation && method === 'GET' ) {
27
13
throw createGraphQLError ( 'Can only perform a mutation operation from a POST request.' , {
28
14
extensions : {
29
15
http : {
@@ -41,15 +27,7 @@ export function usePreventMutationViaGET(): Plugin<YogaInitialContext> {
41
27
return {
42
28
onParse ( ) {
43
29
// We should improve this by getting Yoga stuff from the hook params directly instead of the context
44
- return ( {
45
- result,
46
- context : {
47
- request,
48
- // the `params` might be missing in cases where the user provided
49
- // malformed context to getEnveloped (like `yoga.getEnveloped({})`)
50
- params : { operationName } = { } ,
51
- } ,
52
- } ) => {
30
+ return ( { result, context : { request } } ) => {
53
31
// Run only if this is a Yoga request
54
32
// the `request` might be missing when using graphql-ws for example
55
33
// in which case throwing an error would abruptly close the socket
@@ -67,7 +45,9 @@ export function usePreventMutationViaGET(): Plugin<YogaInitialContext> {
67
45
throw result ;
68
46
}
69
47
70
- assertMutationViaGet ( request . method , result , operationName ) ;
48
+ if ( isDocumentNode ( result ) ) {
49
+ assertMutationViaGet ( request . method , result ) ;
50
+ }
71
51
} ;
72
52
} ,
73
53
} ;
0 commit comments