UNPKG

1.89 kBPlain TextView Raw
1import { tryCatch } from '../../lib/prelude.js'
2import { isOperationDefinitionNode } from '../lib/graphql.js'
3import type { RequestDocument } from './types.js'
4/**
5 * Refactored imports from `graphql` to be more specific, this helps import only the required files (100KiB)
6 * instead of the entire package (greater than 500KiB) where tree-shaking is not supported.
7 * @see https://github.com/jasonkuhrt/graphql-request/pull/543
8 */
9import { type DocumentNode, OperationTypeNode } from 'graphql'
10import { parse } from 'graphql'
11import { print } from 'graphql'
12
13/**
14 * helpers
15 */
16
17const 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
29const 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
41export 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}