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

Remove didReceiveResponse hook #107

Merged
merged 5 commits into from
Dec 5, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
20 changes: 20 additions & 0 deletions .changeset/khaki-cars-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@apollo/datasource-rest': major
---

Reduce responsibility of `didReceiveResponse` hook

The naming of this hook is deceiving; if this hook is overridden it becomes
responsible for returning the parsed body. It was originally introduced in
https://github.com/apollographql/apollo-server/issues/1324, where the author
claims they implemented it due to lack of access to the complete response
(headers) in the fetch methods (get, post, ...). This approach isn't a type safe
way to acoomplish this.

This hook is now just an observability hook which receives a clone of the
response and the request that was sent.

A change following this will introduce the ability to fetch a complete response
(headers included) aside from the provided fetch methods which only return a
body, which will reinstate the functionality that the author of this hook had
originally intended.
24 changes: 14 additions & 10 deletions src/RESTDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,16 +176,10 @@ export abstract class RESTDataSource {
request: FetcherRequestInit,
): CacheOptions | undefined;

protected async didReceiveResponse<TResult = any>(
protected async didReceiveResponse?(
response: FetcherResponse,
_request: RequestOptions,
): Promise<TResult> {
if (response.ok) {
return this.parseBody(response) as any as Promise<TResult>;
} else {
throw await this.errorFromResponse(response);
}
}
request: RequestOptions,
): Promise<void>;

protected didEncounterError(error: Error, _request: RequestOptions) {
throw error;
Expand Down Expand Up @@ -353,9 +347,19 @@ export abstract class RESTDataSource {
cacheKey,
cacheOptions,
});
return await this.didReceiveResponse(response, outgoingRequest);

if (this.didReceiveResponse) {
await this.didReceiveResponse(response.clone(), outgoingRequest);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thought 1: why a clone? Would it be valuable to be able to use this hook to mutate the response if you want? (And it does affect performance negatively to do so.)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thought 2: Seems like another case where we need to include url alongside outgoingRequest (not new in this PR, just while we're here)

}

if (response.ok) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While I do think that didReceiveResponse was the wrong place for this logic, it does kinda feel like it would be helpful for users to be able to differentiate between the error and not cases (eg, maybe you have an API where you want to do non-error for some specific 4xx response, idk). Not sure if this means adding yet another hook, or leaving didReceiveResponse as kinda similar to current semantics but with a better name, or what. (Or just waiting until a user says they can't upgrade without this feature.)

return (await this.parseBody(response)) as TResult;
} else {
throw await this.errorFromResponse(response);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

completely unrelated: the body of errorFromResponse could be rewritten to just pass the response extension directly to the error constructor instead of being written how it is now (and maybe drop the subclasses and put the error extensions directly into the GraphQLError call, idk)

}
} catch (error) {
this.didEncounterError(error as Error, outgoingRequest);
throw error;
}
});
};
Expand Down
42 changes: 42 additions & 0 deletions src/__tests__/RESTDataSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import FormData from 'form-data';
import { GraphQLError } from 'graphql';
import nock from 'nock';
import { nockAfterEach, nockBeforeEach } from './nockAssertions';
import type { FetcherResponse } from '@apollo/utils.fetcher';

const apiUrl = 'https://api.example.com';

Expand Down Expand Up @@ -1145,6 +1146,47 @@ describe('RESTDataSource', () => {
expect(calls).toBe(1);
});
});

describe('didReceiveResponse', () => {
it('is called if implemented', async () => {
const didReceiveResponseMock = jest.fn(async () => {});
const dataSource = new (class extends RESTDataSource {
override baseURL = apiUrl;

getFoo(id: number) {
return this.get(`foo/${id}`);
}

override didReceiveResponse = didReceiveResponseMock;
})();

nock(apiUrl).get('/foo/1').reply(200, { name: 'bar' });
await dataSource.getFoo(1);
expect(didReceiveResponseMock).toHaveBeenCalledTimes(1);
});

it('is ok to consume the body on the response', async () => {
let observedBody;
const dataSource = new (class extends RESTDataSource {
override baseURL = apiUrl;

getFoo(id: number) {
return this.get(`foo/${id}`);
}

override async didReceiveResponse(
response: FetcherResponse,
_outgoingRequest: RequestOptions,
) {
observedBody = await response.json();
}
})();

nock(apiUrl).get('/foo/1').reply(200, { name: 'bar' });
await dataSource.getFoo(1);
expect(observedBody).toEqual({ name: 'bar' });
});
});
});
});
});