Skip to content

Commit

Permalink
[RESTDataSource] refactor to allow overridding the Error class
Browse files Browse the repository at this point in the history
for example if we want to create a `NotFoundError` that will be used when receiving 404s. This way we need to override the bare minimum like

```
class MyDataSource extends RESTDataSource {
  protected errorBaseFromResponseAndMessage(response: Response, message: string): ApolloError {
    if (response.status === 401) return new NotFoundError(message);

    return super.errorBaseFromResponseAndMessage(response, message);
  }
}
```

Also adding it in the RemoteGraphQLDataSource since it has the same code as RESTDataSource, for symmetry purposes.

Signed-off-by: Eduardo Turiño <[email protected]>
  • Loading branch information
eturino committed Jun 25, 2020
1 parent a2d2792 commit 6d4f21a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
15 changes: 7 additions & 8 deletions packages/apollo-datasource-rest/src/RESTDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,16 @@ export abstract class RESTDataSource<TContext = any> extends DataSource {
}
}

protected errorBaseFromResponseAndMessage(response: Response, message: string): ApolloError {
if (response.status === 401) return new AuthenticationError(message);
if (response.status === 403) return new ForbiddenError(message);
return new ApolloError(message);
}

protected async errorFromResponse(response: Response) {
const message = `${response.status}: ${response.statusText}`;

let error: ApolloError;
if (response.status === 401) {
error = new AuthenticationError(message);
} else if (response.status === 403) {
error = new ForbiddenError(message);
} else {
error = new ApolloError(message);
}
const error = this.errorBaseFromResponseAndMessage(response, message);

const body = await this.parseBody(response);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,17 +200,16 @@ export class RemoteGraphQLDataSource<TContext extends Record<string, any> = Reco
}
}

protected errorBaseFromResponseAndMessage(response: Response, message: string): ApolloError {
if (response.status === 401) return new AuthenticationError(message);
if (response.status === 403) return new ForbiddenError(message);
return new ApolloError(message);
}

public async errorFromResponse(response: Response) {
const message = `${response.status}: ${response.statusText}`;

let error: ApolloError;
if (response.status === 401) {
error = new AuthenticationError(message);
} else if (response.status === 403) {
error = new ForbiddenError(message);
} else {
error = new ApolloError(message);
}
const error = this.errorBaseFromResponseAndMessage(response, message);

const body = await this.parseBody(response);

Expand Down

0 comments on commit 6d4f21a

Please sign in to comment.