Skip to content
This repository was archived by the owner on Mar 20, 2023. It is now read-only.

WIP: allow the user to disable HTTP 500 if the response contains only errors #451

Closed
wants to merge 6 commits into from
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ The `graphqlHTTP` function accepts the following options:

* **`pretty`**: If `true`, any JSON response will be pretty-printed.

* **`httpErrorOnEmptyData`**: If `false`, the HTTP status code of the response will not be set to 500 if the response contains only errors, not data.

* **`extensions`**: An optional function for adding additional metadata to the
GraphQL response as a key-value object. The result will be added to
`"extensions"` field in the resulting JSON. This is often a useful place to
Expand Down
16 changes: 15 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ export type OptionsData = {
*/
pretty?: ?boolean,

/**
* A boolean to configure whether HTTP status code should be set to 500
* if the query did not return any data.
* True by default.
*/
httpErrorOnEmptyData?: ?boolean,

/**
* An optional array of validation rules that will be applied on the document
* in additional to those defined by the GraphQL spec.
Expand Down Expand Up @@ -196,6 +203,7 @@ function graphqlHTTP(options: Options): Middleware {
let context;
let params;
let pretty;
let httpErrorOnEmptyData;
let formatErrorFn = formatError;
let validateFn = validate;
let executeFn = execute;
Expand Down Expand Up @@ -244,6 +252,7 @@ function graphqlHTTP(options: Options): Middleware {
const typeResolver = optionsData.typeResolver;
const graphiql = optionsData.graphiql;
context = optionsData.context || request;
httpErrorOnEmptyData = optionsData.httpErrorOnEmptyData !== false;

let validationRules = specifiedRules;
if (optionsData.validationRules) {
Expand Down Expand Up @@ -375,7 +384,12 @@ function graphqlHTTP(options: Options): Middleware {
// Note: Information about the error itself will still be contained in
// the resulting JSON payload.
// http://facebook.github.io/graphql/#sec-Data
if (response.statusCode === 200 && result && !result.data) {
if (
httpErrorOnEmptyData &&
response.statusCode === 200 &&
result &&
!result.data
) {
response.statusCode = 500;
}
// Format any encountered errors.
Expand Down