mirror of
https://github.com/aantron/dream.git
synced 2025-11-09 00:13:46 -05:00
w-graphql-subscription
This example sets up a GraphQL subscription, which receives events that count up to 3:
let count until =
let stream, push = Lwt_stream.create () in
let close () = push None in
Lwt.async begin fun () ->
let rec loop n =
let%lwt () = Lwt_unix.sleep 0.5 in
if n > until
then (close (); Lwt.return_unit)
else (push (Some n); loop (n + 1))
in
loop 1
end;
stream, close
let schema =
let open Graphql_lwt.Schema in
schema []
~subscriptions:[
subscription_field "count"
~typ:(non_null int)
~args:Arg.[arg "until" ~typ:(non_null int)]
~resolve:(fun _info until ->
Lwt.return (Ok (count until)))
]
let default_query =
"subscription {\\n count(until: 3)\\n}\\n"
let () =
Dream.run
@@ Dream.logger
@@ Dream.origin_referer_check
@@ Dream.router [
Dream.any "/graphql" (Dream.graphql Lwt.return schema);
Dream.get "/" (Dream.graphiql ~default_query "/graphql");
]
@@ Dream.not_found
$ cd example/w-graphql-subscriptions
$ npm install esy && npx esy
$ npx esy start
Visit http://localhost:8080 or the playground, and run
subscription {
count(until: 3)
}
...and you should behavior like in the GIF above!
Subscriptions internally use a WebSocket protocol compatible with graphql-ws. This is a new protocol that has succeeded the older subscriptions-transport-ws, though, internally, the two protocols are very similar.
See also:
i-graphqlfor a basic GraphQL example.k-websocketfor direct WebSocket usage.
