Skip to content

Commit

Permalink
Allow plugins to modify the HTTP status code under ERROR conditions.
Browse files Browse the repository at this point in the history
**Note:** This currently only covers error conditions.  Read below for details.

This commit aims to provide user-configurable opt-in to mapping
GraphQL-specific behavior to HTTP status codes under error conditions, which
are not always a 1:1 mapping and often implementation specific.

HTTP status codes — traditionally used for a single resource and meant to
represent the success or failure of an entire request — are less natural to
GraphQL which supports partial successes and failures within the same
response.

For example, some developers might be leveraging client implementations
which rely on HTTP status codes rather than checking the `errors` property
in a GraphQL response for an `AuthenticationError`.  These client
implementations might necessitate a 401 status code.  Or as another example,
perhaps there's some monitoring infrastructure in place that doesn't
understand the idea of partial successes and failures. (Side-note: Apollo
Engine aims to consider these partial failures, and we're continuing to
improve our error observability.  Feedback very much appreciated.)

I've provided some more thoughts on this matter in my comment on:
#2269 (comment)

This implementation falls short of providing the more complete
implementation which I aim to provide via a `didEnounterErrors` life-cycle
hook on the new request pipeline, but it's a baby-step forward.  It was
peculiar, for example, that we couldn't already mostly accomplish this
through the `willSendResponse` life-cycle hook.

Leveraging the `willSendResponse` life-cycle hook has its limitations
though.  Specifically, it requires that the implementer leverage the
already-formatted errors (i.e. those that are destined for the client in the
response), rather than the UN-formatted errors which are more ergonomic to
server-code (read: internal friendly).

Details on the `didEncounterErrors` proposal are roughly discussed in this
comment:
#1709 (comment)

(tl;dr The `didEncounterErrors` hook would receive an `errors` property
which is pre-`formatError`.)

As I opened this commit message with: It's critical to note that this DOES
NOT currently provide the ability to override the HTTP status code for
"success" conditions, which will continue to return "200 OK" for the
time-being.  This requires more digging around in various places to get
correct, and I'd like to give it a bit more consideration.  Errors seem to
be the pressing matter right now.

Hopefully the `didEncounterErrors` hook will come together this week.
  • Loading branch information
abernix committed May 23, 2019
1 parent 7becac4 commit 736ba41
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 3 deletions.
4 changes: 3 additions & 1 deletion packages/apollo-server-core/src/requestPipelineAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
} from 'graphql';
import { KeyValueCache } from 'apollo-server-caching';

type Mutable<T> = { -readonly [P in keyof T]: T[P] };

export interface GraphQLServiceContext {
schema: GraphQLSchema;
schemaHash: string;
Expand All @@ -44,7 +46,7 @@ export interface GraphQLResponse {
data?: Record<string, any>;
errors?: ReadonlyArray<GraphQLFormattedError>;
extensions?: Record<string, any>;
http?: Pick<Response, 'headers'>;
http?: Pick<Response, 'headers'> & Partial<Pick<Mutable<Response>, 'status'>>;
}

export interface GraphQLRequestMetrics {
Expand Down
5 changes: 4 additions & 1 deletion packages/apollo-server-core/src/runHttpQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,10 @@ export async function processHTTPRequest<TContext>(
// doesn't reach GraphQL execution
if (response.errors && typeof response.data === 'undefined') {
// don't include options, since the errors have already been formatted
return throwHttpGraphQLError(400, response.errors as any);
return throwHttpGraphQLError(
(response.http && response.http.status) || 400,
response.errors as any,
);
}

if (response.http) {
Expand Down
64 changes: 63 additions & 1 deletion packages/apollo-server-integration-testsuite/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,19 @@ import {
VERSION,
} from 'apollo-link-persisted-queries';

import { createApolloFetch, ApolloFetch, GraphQLRequest } from 'apollo-fetch';
import {
createApolloFetch,
ApolloFetch,
GraphQLRequest,
ParsedResponse,
} from 'apollo-fetch';
import {
AuthenticationError,
UserInputError,
gql,
Config,
ApolloServerBase,
PluginDefinition,
} from 'apollo-server-core';
import { Headers } from 'apollo-server-env';
import { GraphQLExtension, GraphQLResponse } from 'graphql-extensions';
Expand Down Expand Up @@ -394,6 +400,62 @@ export function testApolloServer<AS extends ApolloServerBase>(
});
});

describe('Plugins', () => {
let apolloFetch: ApolloFetch;
let apolloFetchResponse: ParsedResponse;

const setupApolloServerAndFetchPairForPlugins = async (
plugins: PluginDefinition[] = [],
) => {
const { url: uri } = await createApolloServer({
typeDefs: gql`
type Query {
justAField: String
}
`,
plugins,
});

apolloFetch = createApolloFetch({ uri })
// Store the response so we can inspect it.
.useAfter(({ response }, next) => {
apolloFetchResponse = response;
next();
});
};

it('returns correct status code for a normal operation', async () => {
await setupApolloServerAndFetchPairForPlugins();

const result = await apolloFetch({ query: '{ justAField }' });
expect(result.errors).toBeUndefined();
expect(apolloFetchResponse.status).toEqual(200);
});

it('allows setting a custom status code for an error', async () => {
await setupApolloServerAndFetchPairForPlugins([
{
requestDidStart() {
return {
didResolveOperation() {
throw new Error('known_error');
},
willSendResponse({ response: { http, errors } }) {
if (errors[0].message === 'known_error') {
http.status = 403;
}
},
};
},
},
]);

const result = await apolloFetch({ query: '{ justAField }' });
expect(result.errors).toBeDefined();
expect(apolloFetchResponse.status).toEqual(403);
});
});

describe('formatError', () => {
it('wraps thrown error from validation rules', async () => {
const throwError = jest.fn(() => {
Expand Down

0 comments on commit 736ba41

Please sign in to comment.