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

Add optional url argument to didEncounterErrors hook #242

Merged
merged 4 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 7 additions & 0 deletions .changeset/gorgeous-timers-relax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@apollo/datasource-rest': minor
---

Add `url` parameter to `didEncounterErrors` hook

In previous versions of `RESTDataSource`, the URL of the request was available on the `Request` object passed in to the hook. The `Request` object is no longer passed as an argument, so this restores the availability of the `url` to the hook.
8 changes: 6 additions & 2 deletions src/RESTDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,11 @@ export abstract class RESTDataSource {
request: FetcherRequestInit,
): ValueOrPromise<CacheOptions | undefined>;

protected didEncounterError(_error: Error, _request: RequestOptions) {
protected didEncounterError(
_error: Error,
_request: RequestOptions,
_url: URL,
) {
// left as a no-op instead of an unimplemented optional method to avoid
// breaking an existing use case where one calls
// `super.didEncounterErrors(...)` This could be unimplemented / undefined
Expand Down Expand Up @@ -544,7 +548,7 @@ export abstract class RESTDataSource {
},
};
} catch (error) {
this.didEncounterError(error as Error, outgoingRequest);
this.didEncounterError(error as Error, outgoingRequest, url);
throw error;
}
});
Expand Down
33 changes: 33 additions & 0 deletions src/__tests__/RESTDataSource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2193,6 +2193,39 @@ describe('RESTDataSource', () => {
message: 'I replaced the error entirely',
});
});

it('is called with the url', async () => {
let urlFromDidEncounterError: URL | null = null;
const dataSource = new (class extends RESTDataSource {
override baseURL = 'https://api.example.com';

getFoo() {
return this.get('foo');
}

override didEncounterError(_: Error, __: RequestOptions, url: URL) {
urlFromDidEncounterError = url;
}
})();

nock(apiUrl)
.get('/foo')
.reply(
500,
{
errors: [{ message: 'Houston, we have a problem.' }],
},
{ 'content-type': 'application/json' },
);

try {
await dataSource.getFoo();
} catch {}

expect((urlFromDidEncounterError as any).toString()).toMatch(
'https://api.example.com/foo',
);
});
});
});
});
Expand Down