Improve GraphQL query for TypeScript (#710)

This commit is contained in:
Bob van der Linden
2018-10-25 22:33:16 +02:00
committed by Brandon Keepers
parent 787e36f2ad
commit 35dd36da69
3 changed files with 46 additions and 18 deletions

View File

@@ -1,17 +1,30 @@
import { GitHubAPI, Headers, Variables } from './'
import {
GitHubAPI,
Headers,
Variables
} from './'
class GraphQLError extends Error {
public query: string
public variables: Variables
export interface GraphQLError {
message: string,
locations?: Array<{ line: number, column: number }>,
path?: Array<string | number>,
extensions?: {
[key: string]: any
}
}
constructor (errors: Error[], query: string, variables: Variables) {
super(JSON.stringify(errors))
this.name = 'GraphQLError'
this.query = query
this.variables = variables
export class GraphQLQueryError extends Error {
constructor (
public errors: GraphQLError[],
public query: string,
public variables: Variables,
public data: any
) {
super(`Error(s) occurred executing GraphQL query:\n${JSON.stringify(errors, null, 2)}`)
this.name = 'GraphQLQueryError'
if (Error.captureStackTrace) {
Error.captureStackTrace(this, GraphQLError)
Error.captureStackTrace(this, GraphQLQueryError)
}
}
}
@@ -35,8 +48,13 @@ async function graphql (client: GitHubAPI, query: string, variables: Variables,
variables
})
if (res.data.errors) {
throw new GraphQLError(res.data.errors, query, variables)
if (res.data.errors && res.data.errors.length > 0) {
throw new GraphQLQueryError(
res.data.errors,
query,
variables,
res.data.data
)
}
return res.data.data

View File

@@ -58,7 +58,7 @@ export interface GitHubAPI extends Octokit {
}
request: (RequestOptions: RequestOptions) => Promise<Octokit.AnyResponse>
query: (query: string, variables?: Variables, headers?: Headers) => Promise<GraphQLResponse>
query: (query: string, variables?: Variables, headers?: Headers) => Promise<any>
}
export interface Headers {
@@ -67,6 +67,4 @@ export interface Headers {
export interface Variables { [key: string]: any }
export interface GraphQLResponse {
data: any
}
export { GraphQLError, GraphQLQueryError } from './graphql'

View File

@@ -69,12 +69,24 @@ describe('github/graphql', () => {
})
test('raises errors', async () => {
const response = { 'data': null, 'errors': [{ 'message': 'Unexpected end of document' }] }
const response = { 'data': 'some data', 'errors': [{ 'message': 'Unexpected end of document' }] }
nock('https://api.github.com').post('/graphql', { query })
.reply(200, response)
await expect(github.query(query)).rejects.toThrow('Unexpected end of document')
let thrownError
try {
await github.query(query)
} catch (err) {
thrownError = err
}
expect(thrownError).not.toBeUndefined()
expect(thrownError.name).toEqual('GraphQLQueryError')
expect(thrownError.toString()).toContain('Unexpected end of document')
expect(thrownError.query).toEqual(query)
expect(thrownError.errors).toEqual(response.errors)
expect(thrownError.data).toEqual('some data')
})
})