@@ -14,8 +14,10 @@ import {
14
14
DocumentNode ,
15
15
getOperationAST as graphqlGetOperationAST ,
16
16
OperationTypeNode ,
17
+ GraphQLError ,
17
18
} from 'graphql' ;
18
19
import { isResponse , Request , RequestParams , Response } from './common' ;
20
+ import { areGraphQLErrors } from './utils' ;
19
21
20
22
/**
21
23
* A concrete GraphQL execution context value type.
@@ -98,6 +100,9 @@ export interface HandlerOptions<RawRequest = unknown> {
98
100
* trying to build one internally. In this case, you are responsible for providing
99
101
* a ready set of arguments which will be directly plugged in the operation execution.
100
102
*
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
+ *
101
106
* Omitting the fields `contextValue` from the returned `ExecutionArgs` will use the
102
107
* provided `context` option, if available.
103
108
*
@@ -113,8 +118,9 @@ export interface HandlerOptions<RawRequest = unknown> {
113
118
req : Request < RawRequest > ,
114
119
params : RequestParams ,
115
120
) =>
116
- | Promise < ExecutionArgs | Response | void >
121
+ | Promise < ExecutionArgs | GraphQLError [ ] | Response | void >
117
122
| ExecutionArgs
123
+ | GraphQLError [ ]
118
124
| Response
119
125
| void ;
120
126
/**
@@ -379,9 +385,30 @@ export function createHandler<RawRequest = unknown>(
379
385
}
380
386
381
387
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 ;
385
412
else {
386
413
if ( ! schema ) throw new Error ( 'The GraphQL schema is not provided' ) ;
387
414
0 commit comments