Skip to main content

async_graphql_rocket_ws/
lib.rs

1pub use async_graphql::http::WebSocketProtocols as Protocols;
2use async_graphql::{http::WsMessage, *};
3use futures::{SinkExt, StreamExt};
4use rocket_ws::{Message, WebSocket, frame::CloseFrame};
5
6fn filter_inbound(msg: Message) -> impl Future<Output = Option<Message>> {
7    std::future::ready(match msg {
8        Message::Text(_) | Message::Binary(_) => Some(msg),
9        _ => None,
10    })
11}
12
13fn map_outbound(msg: WsMessage) -> Message {
14    match msg {
15        WsMessage::Text(text) => Message::Text(text.clone()),
16        WsMessage::Close(code, reason) => {
17            let close_frame = Some(CloseFrame {
18                code: code.into(),
19                reason: reason.into(),
20            });
21            Message::Close(close_frame)
22        }
23    }
24}
25
26/// Subscription handler compatible with rocket_ws.
27///
28/// # Examples
29///
30/// ```ignore
31/// #[get("/subscription")]
32/// pub fn subscription(
33///     ws: rocket_ws::WebSocket,
34///     schema: &State<MySchema>,
35/// ) -> rocket_ws::Channel<'static> {
36///     GraphQLSubscription::new(schema, Protocols::GraphQLWS).start(ws)
37/// }
38/// ```
39pub struct GraphQLSubscription<Query, Mutation, Subscription> {
40    schema: async_graphql::Schema<Query, Mutation, Subscription>,
41    protocol: Protocols,
42}
43
44impl<Query, Mutation, Subscription> GraphQLSubscription<Query, Mutation, Subscription>
45where
46    Query: ObjectType + 'static,
47    Mutation: ObjectType + 'static,
48    Subscription: SubscriptionType + 'static,
49{
50    pub fn new(
51        schema: &async_graphql::Schema<Query, Mutation, Subscription>,
52        protocol: Protocols,
53    ) -> Self {
54        Self {
55            schema: schema.clone(),
56            protocol,
57        }
58    }
59
60    pub fn start(self, ws: WebSocket) -> rocket_ws::Channel<'static> {
61        ws.channel(move |stream| {
62            Box::pin(async move {
63                let (mut sink, stream) = futures_util::StreamExt::split(stream);
64
65                // See https://github.com/async-graphql/async-graphql/blob/082201ccd040726410ac1b8a6cf6dc4a1c5179ec/integrations/axum/src/subscription.rs#L265-L276
66                let stream = stream
67                    .take_while(|res| std::future::ready(res.is_ok()))
68                    .map(Result::unwrap)
69                    .filter_map(filter_inbound)
70                    .map(Message::into_data);
71
72                let mut ws =
73                    async_graphql::http::WebSocket::new(self.schema, stream, self.protocol)
74                        .map(map_outbound);
75                while let Some(message) = ws.next().await {
76                    sink.send(message).await.expect("Failed to send message");
77                }
78                eprintln!("WebSocket connection closed");
79                Ok(())
80            })
81        })
82    }
83}