1
0
mirror of https://github.com/actix/examples synced 2025-02-10 20:54:14 +01:00

64 lines
1.7 KiB
Rust
Raw Normal View History

2022-02-06 08:25:38 +00:00
//! Actix Web juniper example
//!
2022-02-06 08:13:24 +00:00
//! A simple example integrating juniper in Actix Web
2019-03-10 19:19:50 -07:00
use std::io;
use std::sync::Arc;
use actix_cors::Cors;
2019-03-10 19:19:50 -07:00
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
use juniper::http::graphiql::graphiql_source;
use juniper::http::GraphQLRequest;
mod schema;
2019-03-10 19:19:50 -07:00
use crate::schema::{create_schema, Schema};
2019-12-08 00:03:53 +06:00
async fn graphiql() -> HttpResponse {
2021-04-26 20:32:32 +09:00
let html = graphiql_source("http://127.0.0.1:8080/graphql", None);
2019-12-08 00:03:53 +06:00
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html)
}
2019-12-08 00:03:53 +06:00
async fn graphql(
st: web::Data<Arc<Schema>>,
data: web::Json<GraphQLRequest>,
2019-12-07 18:59:35 +01:00
) -> Result<HttpResponse, Error> {
2019-12-08 00:03:53 +06:00
let user = web::block(move || {
2021-04-26 20:32:32 +09:00
let res = data.execute_sync(&st, &());
2021-10-07 03:04:59 +01:00
serde_json::to_string(&res)
2019-12-08 00:03:53 +06:00
})
.await?;
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(user))
}
2020-09-12 16:49:45 +01:00
#[actix_web::main]
2019-12-08 00:03:53 +06:00
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
// Create Juniper schema
let schema = std::sync::Arc::new(create_schema());
// Start http server
HttpServer::new(move || {
App::new()
.data(schema.clone())
.wrap(middleware::Logger::default())
.wrap(
Cors::new()
.allowed_methods(vec!["POST", "GET"])
.supports_credentials()
.max_age(3600)
.finish(),
)
2019-12-08 00:03:53 +06:00
.service(web::resource("/graphql").route(web::post().to(graphql)))
.service(web::resource("/graphiql").route(web::get().to(graphiql)))
})
2022-02-17 20:22:36 +00:00
.bind(("127.0.0.1", 8080))?
2019-12-25 20:48:33 +04:00
.run()
2019-12-08 00:03:53 +06:00
.await
}