Skip to content

Commit

Permalink
fix: set error.headers from responses containing a GraphQL error (#159)
Browse files Browse the repository at this point in the history
  • Loading branch information
cliffkoh committed Jul 28, 2020
1 parent 14b6d5d commit 578ca6e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/error.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { ResponseHeaders } from '@octokit/types';
import { GraphQlEndpointOptions, GraphQlQueryResponse } from "./types";

export class GraphqlError<ResponseData> extends Error {
public request: GraphQlEndpointOptions;
constructor(
request: GraphQlEndpointOptions,
response: { data: Required<GraphQlQueryResponse<ResponseData>> }
response: { headers: ResponseHeaders, data: Required<GraphQlQueryResponse<ResponseData>> }
) {
const message = response.data.errors[0].message;
super(message);

Object.assign(this, response.data);
Object.assign(this, { headers: response.headers });
this.name = "GraphqlError";
this.request = request;

Expand Down
7 changes: 7 additions & 0 deletions src/graphql.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { request as Request } from "@octokit/request";
import { ResponseHeaders } from "@octokit/types";
import { GraphqlError } from "./error";
import {
GraphQlEndpointOptions,
Expand Down Expand Up @@ -46,7 +47,13 @@ export function graphql<ResponseData = GraphQlQueryResponseData>(

return request(requestOptions).then((response) => {
if (response.data.errors) {
const headers: ResponseHeaders = {};
for (const key of Object.keys(response.headers)) {
headers[key] = response.headers[key]
}

throw new GraphqlError(requestOptions, {
headers,
data: response.data as Required<GraphQlQueryResponse<ResponseData>>,
});
}
Expand Down
9 changes: 8 additions & 1 deletion test/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ describe("errors", () => {
request: {
fetch: fetchMock
.sandbox()
.post("https://api.github.com/graphql", mockResponse),
.post("https://api.github.com/graphql", {
body: mockResponse,
headers: {
'x-github-request-id': 'C5E6:259A:1351B40:2E88B87:5F1F9C41'
}
}),
},
})
.then((result) => {
Expand All @@ -107,6 +112,8 @@ describe("errors", () => {
expect(error.errors).toStrictEqual(mockResponse.errors);
expect(error.request.query).toEqual(query);
expect(error.data).toStrictEqual(mockResponse.data);
expect(error.headers).toHaveProperty('x-github-request-id');
expect(error.headers['x-github-request-id']).toEqual('C5E6:259A:1351B40:2E88B87:5F1F9C41');
});
});

Expand Down

0 comments on commit 578ca6e

Please sign in to comment.