Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: parse string documents to extract the operationName #325

Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import crossFetch, * as CrossFetch from 'cross-fetch'
import { OperationDefinitionNode } from 'graphql/language/ast'
import { OperationDefinitionNode, DocumentNode } from 'graphql/language/ast'

import { parse } from 'graphql/language/parser'
import { print } from 'graphql/language/printer'
import createRequestBody from './createRequestBody'
import {
Expand Down Expand Up @@ -553,19 +555,36 @@ function getResult(response: Dom.Response): Promise<any> {
* helpers
*/

function resolveRequestDocument(document: RequestDocument): { query: string; operationName?: string } {
if (typeof document === 'string') return { query: document }

function extractOperationName(document: DocumentNode): string | undefined {
let operationName = undefined

let operationDefinitions = document.definitions.filter(
const operationDefinitions = document.definitions.filter(
(definition) => definition.kind === 'OperationDefinition'
) as OperationDefinitionNode[]

if (operationDefinitions.length === 1) {
operationName = operationDefinitions[0].name?.value
}

return operationName
}

function resolveRequestDocument(document: RequestDocument): { query: string; operationName?: string } {
if (typeof document === 'string') {
let operationName = undefined

try {
const parsedDocument = parse(document)
operationName = extractOperationName(parsedDocument)
} catch (err) {
// Failed parsing the document, the operationName will be undefined
}

return { query: document, operationName }
}

const operationName = extractOperationName(document)

return { query: print(document), operationName }
}

Expand Down