1 | import { tryCatch } from '../../lib/prelude.js'
|
2 | import { isOperationDefinitionNode } from '../lib/graphql.js'
|
3 | import type { RequestDocument } from './types.js'
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | import { type DocumentNode, OperationTypeNode } from 'graphql'
|
10 | import { parse } from 'graphql'
|
11 | import { print } from 'graphql'
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const extractOperationName = (document: DocumentNode): string | undefined => {
|
18 | let operationName = undefined
|
19 |
|
20 | const defs = document.definitions.filter(isOperationDefinitionNode)
|
21 |
|
22 | if (defs.length === 1) {
|
23 | operationName = defs[0]!.name?.value
|
24 | }
|
25 |
|
26 | return operationName
|
27 | }
|
28 |
|
29 | const extractIsMutation = (document: DocumentNode): boolean => {
|
30 | let isMutation = false
|
31 |
|
32 | const defs = document.definitions.filter(isOperationDefinitionNode)
|
33 |
|
34 | if (defs.length === 1) {
|
35 | isMutation = defs[0]!.operation === OperationTypeNode.MUTATION
|
36 | }
|
37 |
|
38 | return isMutation
|
39 | }
|
40 |
|
41 | export const analyzeDocument = (
|
42 | document: RequestDocument,
|
43 | excludeOperationName?: boolean,
|
44 | ): { expression: string; operationName: string | undefined; isMutation: boolean } => {
|
45 | const expression = typeof document === `string` ? document : print(document)
|
46 |
|
47 | let isMutation = false
|
48 | let operationName = undefined
|
49 |
|
50 | if (excludeOperationName) {
|
51 | return { expression, isMutation, operationName }
|
52 | }
|
53 |
|
54 | const docNode = tryCatch(() => (typeof document === `string` ? parse(document) : document))
|
55 | if (docNode instanceof Error) {
|
56 | return { expression, isMutation, operationName }
|
57 | }
|
58 |
|
59 | operationName = extractOperationName(docNode)
|
60 | isMutation = extractIsMutation(docNode)
|
61 |
|
62 | return { expression, operationName, isMutation }
|
63 | }
|