UNPKG

2.5 kBPlain TextView Raw
1import { GraphQLClient } from '../classes/GraphQLClient.js'
2import type {
3 GraphQLClientResponse,
4 RawRequestOptions,
5 Variables,
6 VariablesAndRequestHeadersArgs,
7} from '../helpers/types.js'
8
9/**
10 * Send a GraphQL Query to the GraphQL server for execution.
11 */
12export const rawRequest: RawRequest = async <T, V extends Variables>(
13 ...args: RawRequestArgs<V>
14): Promise<GraphQLClientResponse<T>> => {
15 const [urlOrOptions, query, ...variablesAndRequestHeaders] = args
16 const requestOptions = parseRawRequestExtendedArgs<V>(urlOrOptions, query, ...variablesAndRequestHeaders)
17 const client = new GraphQLClient(requestOptions.url)
18 return client.rawRequest<T, V>({
19 ...requestOptions,
20 })
21}
22
23// dprint-ignore
24interface RawRequest {
25 <T, V extends Variables = Variables>(url: string, query: string, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs<V>): Promise<GraphQLClientResponse<T>>
26 <T, V extends Variables = Variables>(options: RawRequestExtendedOptions<V>): Promise<GraphQLClientResponse<T>>
27}
28
29// dprint-ignore
30type RawRequestArgs<V extends Variables> =
31 | [options: RawRequestExtendedOptions<V>, query?: string, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs<V>]
32 | [url: string, query?: string, ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs<V>]
33
34export const parseRawRequestExtendedArgs = <V extends Variables = Variables>(
35 urlOrOptions: string | RawRequestExtendedOptions<V>,
36 query?: string,
37 ...variablesAndRequestHeaders: VariablesAndRequestHeadersArgs<V>
38): RawRequestExtendedOptions<V> => {
39 const [variables, requestHeaders] = variablesAndRequestHeaders
40 return typeof urlOrOptions === `string`
41 ? ({
42 url: urlOrOptions,
43 query: query as string,
44 variables,
45 requestHeaders,
46 signal: undefined,
47 } as unknown as RawRequestExtendedOptions<V>)
48 : urlOrOptions
49}
50
51export type RawRequestExtendedOptions<V extends Variables = Variables> = {
52 url: string
53} & RawRequestOptions<V>
54
55export const parseRawRequestArgs = <V extends Variables = Variables>(
56 queryOrOptions: string | RawRequestOptions<V>,
57 variables?: V,
58 requestHeaders?: HeadersInit,
59): RawRequestOptions<V> => {
60 return (queryOrOptions as RawRequestOptions<V>).query
61 ? (queryOrOptions as RawRequestOptions<V>)
62 : ({
63 query: queryOrOptions as string,
64 variables: variables,
65 requestHeaders: requestHeaders,
66 signal: undefined,
67 } as unknown as RawRequestOptions<V>)
68}