-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql.rs
133 lines (115 loc) · 3.89 KB
/
graphql.rs
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
mod mutation;
mod query;
use std::sync::Arc;
use async_graphql::{http::GraphiQLSource, EmptySubscription, Schema};
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use axum::{
extract::State,
headers::{
authorization::{Bearer, Credentials},
HeaderMap,
},
response::{Html, IntoResponse},
routing, Router,
};
use hyper::StatusCode;
use crate::use_case::{HasStore, Store};
use self::{mutation::MutationRoot, query::QueryRoot};
#[derive(Clone)]
pub struct GraphQLSchema(Schema<QueryRoot, MutationRoot, EmptySubscription>);
impl GraphQLSchema {
pub fn new() -> Self {
Self(Schema::new(QueryRoot, MutationRoot, EmptySubscription))
}
}
pub trait HasGraphQLSchema {
fn graphql_schema(&self) -> &GraphQLSchema;
}
async fn handler<T: HasGraphQLSchema + HasStore>(
State(state): State<T>,
header_map: HeaderMap,
request: GraphQLRequest,
) -> Result<GraphQLResponse, StatusCode> {
let schema = state.graphql_schema();
let store = state.store();
let request = request.into_inner().data(Data {
bearer: match header_map.get(axum::http::header::AUTHORIZATION) {
Some(header_value) => {
Some(Bearer::decode(header_value).ok_or(StatusCode::UNAUTHORIZED)?)
}
None => None,
},
store,
});
Ok(GraphQLResponse::from(schema.0.execute(request).await))
}
async fn graphiql() -> impl IntoResponse {
Html(GraphiQLSource::build().endpoint("/graphql").finish())
}
pub struct Data {
pub bearer: Option<Bearer>,
pub store: Arc<dyn Store + Send + Sync>,
}
pub fn route<T: Clone + HasGraphQLSchema + HasStore + Send + Sync + 'static>() -> Router<T> {
Router::new().route("/graphql", routing::get(graphiql).post(handler::<T>))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
app::App,
test_utils::{send_request, ResponseExt},
};
#[tokio::test]
async fn test_get() -> anyhow::Result<()> {
let app = route().with_state(App::example());
let request = axum::http::Request::builder()
.method("GET")
.uri("/graphql")
.body(axum::body::Body::empty())?;
let response = send_request(app, request).await?;
assert_eq!(response.status(), axum::http::StatusCode::OK);
assert!(response
.into_body_as_string()
.await?
.contains("<title>GraphiQL IDE</title>"));
Ok(())
}
#[tokio::test]
async fn test_post() -> anyhow::Result<()> {
let app = route().with_state(App::example());
let request = axum::http::Request::builder()
.method("POST")
.uri("/graphql")
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(
r#"{"query":"query test_post { hello }"}"#,
))?;
let response = send_request(app, request).await?;
assert_eq!(response.status(), axum::http::StatusCode::OK);
assert_eq!(
response.into_body_as_string().await?,
r#"{"data":{"hello":"Hello, World!"}}"#
);
Ok(())
}
#[tokio::test]
async fn test_post_bearer() -> anyhow::Result<()> {
let app = route().with_state(App::example());
let request = axum::http::Request::builder()
.method("POST")
.uri("/graphql")
.header(axum::http::header::AUTHORIZATION, "Bearer test")
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(
r#"{"query":"query test_post_bearer { bearer }"}"#,
))?;
let response = send_request(app, request).await?;
assert_eq!(response.status(), axum::http::StatusCode::OK);
assert_eq!(
response.into_body_as_string().await?,
r#"{"data":{"bearer":"test"}}"#
);
Ok(())
}
}