1
- import { DocumentNode , GraphQLError , Kind } from 'graphql' ;
1
+ import { DocumentNode , getOperationAST , GraphQLError , OperationDefinitionNode } from 'graphql' ;
2
2
import { Maybe } from '@envelop/core' ;
3
- import { createGraphQLError , isDocumentNode } from '@graphql-tools/utils' ;
3
+ import { createGraphQLError } 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 ( method : string , document : Maybe < DocumentNode > ) {
8
- const isMutation =
9
- document ?. definitions . find ( def => def . kind === Kind . OPERATION_DEFINITION ) ?. operation ===
10
- 'mutation' ;
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 ;
11
15
12
- if ( isMutation && method === 'GET' ) {
16
+ if ( operation ?. operation === 'mutation' && method === 'GET' ) {
13
17
throw createGraphQLError ( 'Can only perform a mutation operation from a POST request.' , {
14
18
extensions : {
15
19
http : {
@@ -27,7 +31,15 @@ export function usePreventMutationViaGET(): Plugin<YogaInitialContext> {
27
31
return {
28
32
onParse ( ) {
29
33
// We should improve this by getting Yoga stuff from the hook params directly instead of the context
30
- return ( { result, context : { request } } ) => {
34
+ return ( {
35
+ result,
36
+ context : {
37
+ request,
38
+ // the `params` might be missing in cases where the user provided
39
+ // malformed context to getEnveloped (like `yoga.getEnveloped({})`)
40
+ params : { operationName } = { } ,
41
+ } ,
42
+ } ) => {
31
43
// Run only if this is a Yoga request
32
44
// the `request` might be missing when using graphql-ws for example
33
45
// in which case throwing an error would abruptly close the socket
@@ -45,9 +57,7 @@ export function usePreventMutationViaGET(): Plugin<YogaInitialContext> {
45
57
throw result ;
46
58
}
47
59
48
- if ( isDocumentNode ( result ) ) {
49
- assertMutationViaGet ( request . method , result ) ;
50
- }
60
+ assertMutationViaGet ( request . method , result , operationName ) ;
51
61
} ;
52
62
} ,
53
63
} ;
0 commit comments