-
Notifications
You must be signed in to change notification settings - Fork 564
/
usePreventMutationViaGET.ts
55 lines (51 loc) · 1.59 KB
/
usePreventMutationViaGET.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { createGraphQLError } from '@graphql-tools/utils'
import { OperationDefinitionNode, getOperationAST, GraphQLError } from 'graphql'
import { YogaInitialContext } from '../../types'
import { Plugin } from '../types'
export function usePreventMutationViaGET(): Plugin<YogaInitialContext> {
return {
onParse() {
// We should improve this by getting Yoga stuff from the hook params directly instead of the context
return ({ result, context: { request, operationName } }) => {
if (result instanceof Error) {
if (result instanceof GraphQLError) {
result.extensions.http = {
status: 400,
}
}
throw result
}
const operation: OperationDefinitionNode | undefined = result
? getOperationAST(result, operationName) ?? undefined
: undefined
if (!operation) {
throw createGraphQLError(
'Could not determine what operation to execute.',
{
extensions: {
http: {
status: 400,
},
},
},
)
}
if (operation.operation === 'mutation' && request.method === 'GET') {
throw createGraphQLError(
'Can only perform a mutation operation from a POST request.',
{
extensions: {
http: {
status: 405,
headers: {
Allow: 'POST',
},
},
},
},
)
}
}
},
}
}