Skip to content

Commit

Permalink
* Get query's operation name from vars, fixes graffle-js#64
Browse files Browse the repository at this point in the history
  • Loading branch information
adebisi-fa committed May 28, 2020
1 parent d7f4f2f commit 2d77cc1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
/// <reference lib="dom" />

import { ClientError, GraphQLError, Variables } from './types'
import { ClientError, GraphQLError, Variables, HasOperationNameKey } from './types'

export { ClientError } from './types'

export class GraphQLClient {
private url: string
private options: RequestInit
private options: RequestInit & HasOperationNameKey

constructor(url: string, options?: RequestInit) {
constructor(url: string, options?: RequestInit & HasOperationNameKey) {
this.url = url
this.options = options || {}
}

private extractOperationName(operationNameKey?: string, variables?: Variables) {
if (!operationNameKey)
operationNameKey = "__operation";

var operationName = variables ? variables[operationNameKey] : null;
if (operationName) {
// Cleanup operationNameKey from variables
delete (variables as any)[operationNameKey];
return { operationName }
}
return null;
}

async rawRequest<T = any>(
query: string,
variables?: Variables
Expand All @@ -23,11 +36,12 @@ export class GraphQLClient {
status: number
errors?: GraphQLError[]
}> {
const { headers, ...others } = this.options
const { headers, operationNameKey, ...others } = this.options

const body = JSON.stringify({
query,
variables: variables ? variables : undefined,
...this.extractOperationName(operationNameKey, variables)
})

const response = await fetch(this.url, {
Expand All @@ -52,11 +66,12 @@ export class GraphQLClient {
}

async request<T = any>(query: string, variables?: Variables): Promise<T> {
const { headers, ...others } = this.options
const { headers, operationNameKey, ...others } = this.options

const body = JSON.stringify({
query,
variables: variables ? variables : undefined,
...this.extractOperationName(operationNameKey, variables)
})

const response = await fetch(this.url, {
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
export type Variables = { [key: string]: any }

export interface HasOperationNameKey {
operationNameKey?: string;
}

export interface GraphQLError {
message: string
locations: { line: number; column: number }[]
Expand Down

0 comments on commit 2d77cc1

Please sign in to comment.