forked from fsprojects/FSharp.Data.GraphQL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphQLClient.fs
More file actions
180 lines (167 loc) · 8.67 KB
/
Copy pathGraphQLClient.fs
File metadata and controls
180 lines (167 loc) · 8.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/// The MIT License (MIT)
/// Copyright (c) 2016 Bazinga Technologies Inc
namespace FSharp.Data.GraphQL
open System
open System.Collections.Generic
open System.Net.Http
open FSharp.Data.GraphQL
open FSharp.Data.GraphQL.Client
open System.Text
open ReflectionPatterns
open System.Threading
/// A requrest object for making GraphQL calls using the GraphQL client module.
type GraphQLRequest =
/// Gets the URL of the GraphQL server which will be called.
{ ServerUrl : string
/// Gets custom HTTP Headers to pass with each call using this request.
HttpHeaders: seq<string * string>
/// Gets the name of the operation that should run on the server.
OperationName : string option
/// Gets the query string which should be executed on the GraphQL server.
Query : string
/// Gets variables to be sent with the query.
Variables : (string * obj) [] }
/// Executes calls to GraphQL servers and return their responses.
module GraphQLClient =
let private ensureSuccessCode (response : Async<HttpResponseMessage>) =
async {
let! response = response
return response.EnsureSuccessStatusCode()
}
let private addHeaders (httpHeaders : seq<string * string>) (requestMessage : HttpRequestMessage) =
if not (isNull httpHeaders)
then httpHeaders |> Seq.iter (fun (name, value) -> requestMessage.Headers.Add(name, value))
let private postAsync (invoker : HttpMessageInvoker) (serverUrl : string) (httpHeaders : seq<string * string>) (content : HttpContent) =
async {
use requestMessage = new HttpRequestMessage(HttpMethod.Post, serverUrl)
requestMessage.Content <- content
addHeaders httpHeaders requestMessage
let! response = invoker.SendAsync(requestMessage, CancellationToken.None) |> Async.AwaitTask |> ensureSuccessCode
let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask
return content
}
let private getAsync (invoker : HttpMessageInvoker) (serverUrl : string) =
async {
use requestMessage = new HttpRequestMessage(HttpMethod.Get, serverUrl)
let! response = invoker.SendAsync(requestMessage, CancellationToken.None) |> Async.AwaitTask |> ensureSuccessCode
let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask
return content
}
/// Sends a request to a GraphQL server asynchronously.
let sendRequestAsync (connection : GraphQLClientConnection) (request : GraphQLRequest) =
async {
let invoker = connection.Invoker
let variables =
match request.Variables with
| null | [||] -> JsonValue.Null
| _ -> Map.ofArray request.Variables |> Serialization.toJsonValue
let operationName =
match request.OperationName with
| Some x -> JsonValue.String x
| None -> JsonValue.Null
let requestJson =
[| "operationName", operationName
"query", JsonValue.String request.Query
"variables", variables |]
|> JsonValue.Record
let content = new StringContent(requestJson.ToString(), Encoding.UTF8, "application/json")
return! postAsync invoker request.ServerUrl request.HttpHeaders content
}
/// Sends a request to a GraphQL server.
let sendRequest client request =
sendRequestAsync client request
|> Async.RunSynchronously
/// Executes an introspection schema request to a GraphQL server asynchronously.
let sendIntrospectionRequestAsync (connection : GraphQLClientConnection) (serverUrl : string) httpHeaders =
let sendGet() = async { return! getAsync connection.Invoker serverUrl }
let rethrow (exns : exn list) =
let rec mapper (acc : string) (exns : exn list) =
let aggregateMapper (ex : AggregateException) = mapper "" (List.ofSeq ex.InnerExceptions)
match exns with
| [] -> acc.TrimEnd()
| ex :: tail ->
match ex with
| :? AggregateException as ex -> mapper (acc + aggregateMapper ex + " ") tail
| ex -> mapper (acc + ex.Message + " ") tail
failwithf "Failure trying to recover introspection schema from server at \"%s\". Errors: %s" serverUrl (mapper "" exns)
async {
try return! sendGet()
with getex ->
let request =
{ ServerUrl = serverUrl
HttpHeaders = httpHeaders
OperationName = None
Query = Introspection.IntrospectionQuery
Variables = [||] }
try return! sendRequestAsync connection request
with postex -> return rethrow [getex; postex]
}
/// Executes an introspection schema request to a GraphQL server.
let sendIntrospectionRequest client serverUrl httpHeaders =
sendIntrospectionRequestAsync client serverUrl httpHeaders
|> Async.RunSynchronously
/// Executes a multipart request to a GraphQL server asynchronously.
let sendMultipartRequestAsync (connection : GraphQLClientConnection) (request : GraphQLRequest) =
async {
let invoker = connection.Invoker
let boundary = "----GraphQLProviderBoundary" + (Guid.NewGuid().ToString("N"))
let content = new MultipartContent("form-data", boundary)
let files =
let rec tryMapFileVariable (name: string, value : obj) =
match value with
| null | :? string -> None
| :? Upload as x -> Some [|name, x|]
| OptionValue x ->
x |> Option.bind (fun x -> tryMapFileVariable (name, x))
| :? IDictionary<string, obj> as x ->
x |> Seq.collect (fun kvp -> tryMapFileVariable (name + "." + (kvp.Key.FirstCharLower()), kvp.Value) |> Option.defaultValue [||])
|> Array.ofSeq
|> Some
| EnumerableValue x ->
x |> Array.mapi (fun ix x -> tryMapFileVariable (name + "." + (ix.ToString()), x))
|> Array.collect (Option.defaultValue [||])
|> Some
| _ -> None
request.Variables |> Array.collect (tryMapFileVariable >> (Option.defaultValue [||]))
let operationContent =
let variables =
match request.Variables with
| null | [||] -> JsonValue.Null
| _ -> request.Variables |> Map.ofArray |> Serialization.toJsonValue
let operationName =
match request.OperationName with
| Some x -> JsonValue.String x
| None -> JsonValue.Null
let json =
[| "operationName", operationName
"query", JsonValue.String request.Query
"variables", variables |]
|> JsonValue.Record
let content = new StringContent(json.ToString(JsonSaveOptions.DisableFormatting))
content.Headers.Add("Content-Disposition", "form-data; name=\"operations\"")
content
content.Add(operationContent)
let mapContent =
let files =
files
|> Array.mapi (fun ix (name, _) -> ix.ToString(), JsonValue.Array [| JsonValue.String ("variables." + name) |])
|> JsonValue.Record
let content = new StringContent(files.ToString(JsonSaveOptions.DisableFormatting))
content.Headers.Add("Content-Disposition", "form-data; name=\"map\"")
content
content.Add(mapContent)
let fileContents =
files
|> Array.mapi (fun ix (_, value) ->
let content = new StreamContent(value.Stream)
content.Headers.Add("Content-Disposition", sprintf "form-data; name=\"%i\"; filename=\"%s\"" ix value.FileName)
content.Headers.Add("Content-Type", value.ContentType)
content)
fileContents |> Array.iter content.Add
let! result = postAsync invoker request.ServerUrl request.HttpHeaders content
return result
}
/// Executes a multipart request to a GraphQL server.
let sendMultipartRequest connection request =
sendMultipartRequestAsync connection request
|> Async.RunSynchronously