2019-12-07 18:59:24 +01:00
|
|
|
use actix_web::{web, Error, HttpResponse};
|
2019-12-07 15:16:46 +01:00
|
|
|
use juniper::http::graphiql::graphiql_source;
|
|
|
|
use juniper::http::GraphQLRequest;
|
|
|
|
|
|
|
|
use crate::db::Pool;
|
2019-12-07 18:59:24 +01:00
|
|
|
use crate::schemas::root::{create_schema, Context, Schema};
|
2019-12-07 15:16:46 +01:00
|
|
|
|
2019-12-07 18:59:24 +01:00
|
|
|
pub async fn graphql(
|
2019-12-07 15:16:46 +01:00
|
|
|
pool: web::Data<Pool>,
|
2020-09-20 19:24:14 +02:00
|
|
|
schema: web::Data<Schema>,
|
2019-12-07 15:16:46 +01:00
|
|
|
data: web::Json<GraphQLRequest>,
|
2019-12-07 18:59:24 +01:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2019-12-07 15:16:46 +01:00
|
|
|
let ctx = Context {
|
|
|
|
dbpool: pool.get_ref().to_owned(),
|
|
|
|
};
|
2019-12-07 18:59:24 +01:00
|
|
|
let res = web::block(move || {
|
2021-04-26 13:32:32 +02:00
|
|
|
let res = data.execute_sync(&schema, &ctx);
|
2021-10-07 04:04:59 +02:00
|
|
|
serde_json::to_string(&res)
|
2019-12-07 15:16:46 +01:00
|
|
|
})
|
2019-12-07 18:59:24 +01:00
|
|
|
.await
|
|
|
|
.map_err(Error::from)?;
|
|
|
|
|
|
|
|
Ok(HttpResponse::Ok()
|
|
|
|
.content_type("application/json")
|
|
|
|
.body(res))
|
2019-12-07 15:16:46 +01:00
|
|
|
}
|
|
|
|
|
2019-12-07 18:59:24 +01:00
|
|
|
pub async fn graphql_playground() -> HttpResponse {
|
2019-12-07 15:16:46 +01:00
|
|
|
HttpResponse::Ok()
|
|
|
|
.content_type("text/html; charset=utf-8")
|
2021-04-26 13:32:32 +02:00
|
|
|
.body(graphiql_source("/graphql", None))
|
2019-12-07 15:16:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn register(config: &mut web::ServiceConfig) {
|
|
|
|
config
|
2020-09-20 19:24:14 +02:00
|
|
|
.data(create_schema())
|
2019-12-07 18:59:24 +01:00
|
|
|
.route("/graphql", web::post().to(graphql))
|
2019-12-07 15:16:46 +01:00
|
|
|
.route("/graphiql", web::get().to(graphql_playground));
|
2019-12-07 18:59:24 +01:00
|
|
|
}
|