import { GraphQLClient } from '../classes/GraphQLClient.js' import type { RequestDocument, Variables } from '../helpers/types.js' export type BatchRequestDocument = { document: RequestDocument variables?: V } export interface BatchRequestsOptions { documents: BatchRequestDocument[] requestHeaders?: HeadersInit signal?: RequestInit['signal'] } export interface BatchRequestsExtendedOptions extends BatchRequestsOptions { url: string } /** * Send a batch of GraphQL Document to the GraphQL server for execution. * * @example * * ```ts * // You can pass a raw string * * await batchRequests('https://foo.bar/graphql', [ * { * query: ` * { * query { * users * } * }` * }, * { * query: ` * { * query { * users * } * }` * }]) * * // You can also pass a GraphQL DocumentNode as query. Convenient if you * // are using graphql-tag package. * * import gql from 'graphql-tag' * * await batchRequests('https://foo.bar/graphql', [{ query: gql`...` }]) * ``` */ export const batchRequests: BatchRequests = async (...args: BatchRequestsArgs) => { const params = parseBatchRequestsArgsExtended(args) const client = new GraphQLClient(params.url) return client.batchRequests(params) } type BatchRequestsArgs = | [url: string, documents: BatchRequestDocument[], requestHeaders?: HeadersInit] | [options: BatchRequestsExtendedOptions] export const parseBatchRequestsArgsExtended = (args: BatchRequestsArgs): BatchRequestsExtendedOptions => { if (args.length === 1) { return args[0] } else { return { url: args[0], documents: args[1], requestHeaders: args[2], signal: undefined, } } } // dprint-ignore interface BatchRequests { (url: string, documents: BatchRequestDocument[], requestHeaders?: HeadersInit): Promise (options: BatchRequestsExtendedOptions): Promise } export type BatchResult = [Result, ...Result[]] interface Result { data: Data } export const parseBatchRequestArgs = ( documentsOrOptions: BatchRequestDocument[] | BatchRequestsOptions, requestHeaders?: HeadersInit, ): BatchRequestsOptions => { // eslint-disable-next-line return (documentsOrOptions as BatchRequestsOptions).documents ? (documentsOrOptions as BatchRequestsOptions) : { documents: documentsOrOptions as BatchRequestDocument[], requestHeaders: requestHeaders, signal: undefined, } }