forked from talex5/get-activity
-
Notifications
You must be signed in to change notification settings - Fork 2
/
graphql.ml
32 lines (29 loc) · 1.02 KB
/
graphql.ml
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
open Lwt.Infix
let graphql_endpoint = Uri.of_string "https://api.github.com/graphql"
let ( / ) a b = Yojson.Safe.Util.member b a
let exec ?variables token query =
let body =
`Assoc (
("query", `String query) ::
(match variables with
| None -> []
| Some v -> ["variables", `Assoc v])
)
|> Yojson.Safe.to_string
|> Cohttp_lwt.Body.of_string
in
let headers = Cohttp.Header.init_with "Authorization" ("bearer " ^ token) in
Cohttp_lwt_unix.Client.post ~headers ~body graphql_endpoint >>=
fun (resp, body) ->
Cohttp_lwt.Body.to_string body >|= fun body ->
match Cohttp.Response.status resp with
| `OK ->
let json = Yojson.Safe.from_string body in
begin match json / "errors" with
| `Null -> json
| _errors ->
Fmt.failwith "@[<v2>GitHub returned errors: %a@]" (Yojson.Safe.pretty_print ~std:true) json;
end
| err -> Fmt.failwith "@[<v2>Error performing GraphQL query on GitHub: %s@,%s@]"
(Cohttp.Code.string_of_status err)
body