1
0
mirror of https://github.com/actix/examples synced 2025-02-11 13:12:51 +01:00
examples/juniper/src/main.rs

56 lines
1.3 KiB
Rust
Raw Normal View History

//! Actix web juniper example
//!
//! A simple example integrating juniper in actix-web
2019-03-10 19:19:50 -07:00
use std::io;
use std::sync::Arc;
#[macro_use]
extern crate juniper;
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-03-10 19:19:50 -07:00
fn graphiql() -> HttpResponse {
2019-12-07 18:59:35 +01:00
let html = graphiql_source("http://127.0.0.1:8080/graphql");
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html)
}
2018-05-08 11:08:43 -07:00
fn graphql(
2019-12-07 18:59:35 +01:00
st: web::Data<Arc<Schema>>,
data: web::Json<GraphQLRequest>,
) -> Result<HttpResponse, Error> {
let res = data.execute(&st, &());
let user = serde_json::to_string(&res)?;
Ok(
HttpResponse::Ok()
.content_type("application/json")
.body(user)
)
}
2019-03-10 19:19:50 -07:00
fn main() -> io::Result<()> {
2019-12-07 18:59:35 +01:00
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())
.service(web::resource("/graphql").route(web::post().to_async(graphql)))
.service(web::resource("/graphiql").route(web::get().to(graphiql)))
})
.bind("127.0.0.1:8080")?
.run()
}