@@ -6,7 +6,7 @@ import pTimeout from 'p-timeout'
66import sjson from 'secure-json-parse'
77
88import { KeyValueCache } from 'apollo-server-caching'
9- import { ResponseData } from 'undici/types/dispatcher'
9+ import Dispatcher , { ResponseData } from 'undici/types/dispatcher'
1010import { toApolloError } from 'apollo-server-errors'
1111import { EventEmitter } from 'stream'
1212import { Logger } from 'apollo-server-types'
@@ -44,10 +44,10 @@ interface Dictionary<T> {
4444
4545export type RequestOptions = Omit < Partial < Request > , 'origin' | 'path' | 'method' >
4646
47- export type Request = {
47+ export type Request < T = unknown > = {
4848 context : Dictionary < string >
4949 query : Dictionary < string | number >
50- body : any
50+ body : T
5151 signal ?: AbortSignal | EventEmitter | null
5252 json ?: boolean
5353 origin : string
@@ -266,23 +266,23 @@ export abstract class HTTPDataSource<TContext = any> extends DataSource {
266266 request : Request ,
267267 cacheKey : string ,
268268 ) : Promise < Response < TResult > > {
269- await this . onRequest ?.( request )
270-
271269 try {
272- const requestOptions = {
270+ if ( request . body !== null && typeof request . body === 'object' ) {
271+ if ( request . headers [ 'content-type' ] === undefined ) {
272+ request . headers [ 'content-type' ] = 'application/json; charset=utf-8'
273+ }
274+ request . body = JSON . stringify ( request . body )
275+ }
276+
277+ await this . onRequest ?.( request )
278+
279+ const requestOptions : Dispatcher . RequestOptions = {
273280 method : request . method ,
274281 origin : request . origin ,
275282 path : request . path ,
276- body : request . body ,
277283 headers : request . headers ,
278284 signal : request . signal ,
279- }
280-
281- if ( request . json === true ) {
282- if ( requestOptions . headers [ 'content-type' ] === undefined ) {
283- requestOptions . headers [ 'content-type' ] = 'application/json; charset=utf-8'
284- }
285- requestOptions . body = JSON . stringify ( requestOptions . body )
285+ body : request . body as string ,
286286 }
287287
288288 const responseData = await this . pool . request ( requestOptions )
@@ -295,7 +295,7 @@ export abstract class HTTPDataSource<TContext = any> extends DataSource {
295295
296296 let json = null
297297 if ( responseData . headers [ 'content-type' ] ?. includes ( 'application/json' ) ) {
298- if ( data !== ' ') {
298+ if ( data . length && typeof data === 'string ') {
299299 json = sjson . parse ( data )
300300 }
301301 }
0 commit comments