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

Allow custom fetch instance to be passed into remote gateway datasource #3754

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export class RemoteGraphQLDataSource implements GraphQLDataSource {
}

url!: string;
customFetch!: typeof fetch;

async process<TContext>({
request,
Expand Down Expand Up @@ -58,9 +59,10 @@ export class RemoteGraphQLDataSource implements GraphQLDataSource {
};

const httpRequest = new Request(request.http.url, options);
const customFetch = this.customFetch || fetch;

try {
const httpResponse = await fetch(httpRequest);
const httpResponse = await customFetch(httpRequest);

const body = await this.didReceiveResponse(
httpResponse,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,34 @@ describe('constructing requests', () => {
body: { query: '{ me { name } }', variables: { id: '1' } },
});
});

it('accepts custom fetch instance', async () => {
const customFetchMock = jest.fn(() => {
return new Response(JSON.stringify({ data: { me: 'james' } }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
});

const DataSource = new RemoteGraphQLDataSource({
url: 'https://api.example.com/foo',
customFetch: customFetchMock,
});

const { data } = await DataSource.process({
request: {
query: '{ me { name } }',
},
});

expect(data).toEqual({ me: 'james' });
expect(fetch).toBeCalledTimes(0);
expect(customFetchMock).toBeCalledTimes(1);
expect(customFetchMock).toHaveFetched({
url: 'https://api.example.com/foo',
body: { query: '{ me { name } }' },
});
});
});

describe('willSendRequest', () => {
Expand Down Expand Up @@ -131,7 +159,11 @@ describe('didReceiveResponse', () => {
request: Request,
context: TContext,
): Promise<TResult> {
const body = await super.didReceiveResponse<TResult>(response, request, context);
const body = await super.didReceiveResponse<TResult>(
response,
request,
context,
);
const surrogateKeys = request.headers.get('surrogate-keys');
if (surrogateKeys) {
(context as any).surrogateKeys.push(...surrogateKeys.split(' '));
Expand Down