1- module Schema = Graphql_schema. Make (Lwt )
1+ open Graphql
2+
3+ module Schema = Graphql_schema. Make (Lwt )
4+
5+ module Server = struct
6+ module C = Cohttp_lwt_unix
7+ open Lwt
8+
9+ let static_file_response ?(encoding =`None ) path =
10+ match Assets. read path with
11+ | Some body -> C.Server. respond_string ~status: `OK ~body ()
12+ | None -> C.Server. respond_string ~status: `Not_found ~body: " " ()
13+
14+ let json_err = function
15+ | Ok _ as ok -> ok
16+ | Error err -> Error (`String err)
17+
18+ let execute_query ctx schema variables query =
19+ let open Lwt_result in
20+ Lwt. return @@ json_err @@ Graphql_parser. parse query >> = fun doc ->
21+ Schema. execute schema ctx ~variables doc
22+
23+ let execute_request ctx schema req body =
24+ Cohttp_lwt_body. to_string body >> = fun body' ->
25+ Lwt_io. printf " Body: %s\n " body';
26+ let json = Yojson.Basic. from_string body' in
27+ let query = Yojson.Basic. (json |> Util. member " query" |> Util. to_string) in
28+ let variables = try Yojson.Basic.Util. (json |> member " variables" |> to_assoc) with _ -> [] in
29+ Lwt_io. printf " Query: %s\n " query;
30+ let result = execute_query ctx schema (variables :> (string * Graphql_parser.const_value ) list ) query in
31+ result >> = function
32+ | Ok data ->
33+ let body = Yojson.Basic. to_string data in
34+ C.Server. respond_string ~status: `OK ~body ()
35+ | Error err ->
36+ let body = Yojson.Basic. to_string err in
37+ C.Server. respond_error ~body ()
38+
39+ let mk_callback mk_context schema conn (req : Cohttp.Request.t ) body =
40+ Lwt_io. printf " Req: %s\n " req.resource;
41+ let req_path = Cohttp.Request. uri req |> Uri. path in
42+ let path_parts = Str. (split (regexp " /" ) req_path) in
43+ match req.meth, path_parts with
44+ | `GET , [" graphql" ] -> static_file_response " index.html"
45+ | `GET , [" graphql" ; path] -> static_file_response path
46+ | `POST , [" graphql" ] -> execute_request (mk_context () ) schema req body
47+ | _ -> C.Server. respond_string ~status: `Not_found ~body: " " ()
48+
49+ let start ?(port =8080 ) ~ctx schema =
50+ let callback = mk_callback ctx schema in
51+ C.Server. create ~mode: (`TCP (`Port port)) (C.Server. make ~callback () )
52+ end
0 commit comments