@@ -14,8 +14,10 @@ import {
1414 DocumentNode ,
1515 getOperationAST as graphqlGetOperationAST ,
1616 OperationTypeNode ,
17+ GraphQLError ,
1718} from 'graphql' ;
1819import { isResponse , Request , RequestParams , Response } from './common' ;
20+ import { areGraphQLErrors } from './utils' ;
1921
2022/**
2123 * A concrete GraphQL execution context value type.
@@ -98,6 +100,9 @@ export interface HandlerOptions<RawRequest = unknown> {
98100 * trying to build one internally. In this case, you are responsible for providing
99101 * a ready set of arguments which will be directly plugged in the operation execution.
100102 *
103+ * If you return an array of `GraphQLError` from the callback, they will be reported
104+ * to the client while complying with the spec.
105+ *
101106 * Omitting the fields `contextValue` from the returned `ExecutionArgs` will use the
102107 * provided `context` option, if available.
103108 *
@@ -113,8 +118,9 @@ export interface HandlerOptions<RawRequest = unknown> {
113118 req : Request < RawRequest > ,
114119 params : RequestParams ,
115120 ) =>
116- | Promise < ExecutionArgs | Response | void >
121+ | Promise < ExecutionArgs | GraphQLError [ ] | Response | void >
117122 | ExecutionArgs
123+ | GraphQLError [ ]
118124 | Response
119125 | void ;
120126 /**
@@ -379,9 +385,30 @@ export function createHandler<RawRequest = unknown>(
379385 }
380386
381387 let args : ExecutionArgs ;
382- const maybeResOrExecArgs = await onSubscribe ?.( req , params ) ;
383- if ( isResponse ( maybeResOrExecArgs ) ) return maybeResOrExecArgs ;
384- else if ( maybeResOrExecArgs ) args = maybeResOrExecArgs ;
388+ const maybeResErrsOrArgs = await onSubscribe ?.( req , params ) ;
389+ if ( isResponse ( maybeResErrsOrArgs ) ) return maybeResErrsOrArgs ;
390+ else if ( areGraphQLErrors ( maybeResErrsOrArgs ) )
391+ return [
392+ JSON . stringify ( { errors : maybeResErrsOrArgs } ) ,
393+ {
394+ ...( acceptedMediaType === 'application/json'
395+ ? {
396+ status : 200 ,
397+ statusText : 'OK' ,
398+ }
399+ : {
400+ status : 400 ,
401+ statusText : 'Bad Request' ,
402+ } ) ,
403+ headers : {
404+ 'content-type' :
405+ acceptedMediaType === 'application/json'
406+ ? 'application/json; charset=utf-8'
407+ : 'application/graphql+json; charset=utf-8' ,
408+ } ,
409+ } ,
410+ ] ;
411+ else if ( maybeResErrsOrArgs ) args = maybeResErrsOrArgs ;
385412 else {
386413 if ( ! schema ) throw new Error ( 'The GraphQL schema is not provided' ) ;
387414
0 commit comments