Skip to content

Commit

Permalink
[executors/http] wrap upstream graphql errors in a GraphQLError insta…
Browse files Browse the repository at this point in the history
…nce (#6299)

* [executors/http] wrap upstream graphql errors in a GraphQLError instance

* add guards

* Update packages/executors/http/tests/buildHTTPExecutor.test.ts

* F

* Improve test

* changeset

* Prettier

---------

Co-authored-by: Arda TANRIKULU <[email protected]>
  • Loading branch information
EmrysMyrddin and ardatan committed Jul 5, 2024
1 parent 6ae0d90 commit b0ffac8
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/dry-rice-design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@graphql-tools/executor-http": patch
---

When proxying the requests to the HTTP executor, it should return \`GraphQLError\` instances in \`errors\` array
21 changes: 21 additions & 0 deletions packages/executors/http/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,27 @@ export function buildHTTPExecutor(
],
};
}
if (Array.isArray(parsedResult.errors)) {
return {
...parsedResult,
errors: parsedResult.errors.map(
({
message,
...options
}: {
message: string;
extensions: Record<string, unknown>;
}) =>
createGraphQLError(message, {
...options,
extensions: {
code: 'DOWNSTREAM_SERVICE_ERROR',
...(options.extensions || {}),
},
}),
),
};
}
return parsedResult;
} catch (e: any) {
return {
Expand Down
29 changes: 27 additions & 2 deletions packages/executors/http/tests/buildHTTPExecutor.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createServer, Server } from 'http';
import { parse } from 'graphql';
import { createGraphQLError, ExecutionResult } from '@graphql-tools/utils';
import { GraphQLError, parse } from 'graphql';
import { createGraphQLError, ExecutionResult, isAsyncIterable } from '@graphql-tools/utils';
import { ReadableStream, Request, Response } from '@whatwg-node/fetch';
import { assertAsyncIterable } from '../../../loaders/url/tests/test-utils.js';
import { buildHTTPExecutor } from '../src/index.js';
Expand Down Expand Up @@ -255,4 +255,29 @@ describe('buildHTTPExecutor', () => {
}),
).toThrow('Executor was disposed. Aborting execution');
});
it('should return return GraphqlError instances', async () => {
const executor = buildHTTPExecutor({
useGETForQueries: true,
fetch() {
return Response.json({ errors: [{ message: 'test error' }] });
},
});

const result = await executor({
document: parse(/* GraphQL */ `
query {
hello
}
`),
});

if (isAsyncIterable(result)) {
throw new Error('Expected result to be an ExecutionResult');
}

expect(result.errors?.[0]).toBeInstanceOf(GraphQLError);
expect(result.errors?.[0]?.extensions).toMatchObject({
code: 'DOWNSTREAM_SERVICE_ERROR',
});
});
});

0 comments on commit b0ffac8

Please sign in to comment.