Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Last active July 13, 2022 05:43
Show Gist options
  • Save acro5piano/25434e229368c3f69428354f8df33c85 to your computer and use it in GitHub Desktop.
Save acro5piano/25434e229368c3f69428354f8df33c85 to your computer and use it in GitHub Desktop.
actix-web + async-graphql using routing macro and context
mod db;
mod entities;
mod graphql;
use crate::db::create_db_pool;
use crate::graphql::schema::{create_schema, AppSchema};
use actix_cors::Cors;
use actix_web::{get, middleware::Logger, post, web::Data, App, HttpServer, Responder};
use async_graphql_actix_web::{GraphQLRequest, GraphQLResponse};
use dotenv::dotenv;
use sqlx::postgres::PgPool;
use std::fs;
use std::sync::Arc;
#[get("/health")]
async fn health() -> impl Responder {
format!("ok")
}
#[post("/graphql")]
async fn post_graphql(
schema: Data<AppSchema>,
db_pool_data: Data<PgPool>,
req: GraphQLRequest,
) -> GraphQLResponse {
let db_pool = db_pool_data.get_ref().clone();
schema.execute(req.into_inner().data(db_pool)).await.into()
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("debug"));
let db_pool = Arc::new(create_db_pool().await.expect("Cannot connect to database"));
let schema = Arc::new(create_schema());
let schema_str = schema.sdl();
fs::write("schema.graphql", schema_str).unwrap_or_else(|e| {
log::warn!("Unable to write schema file: {:?}", e);
});
HttpServer::new(move || {
let cors = Cors::default()
.allow_any_origin()
.allow_any_method()
.allow_any_header()
.max_age(3600);
App::new()
.wrap(cors)
.wrap(Logger::default())
.app_data(Data::from(schema.clone()))
.app_data(Data::from(db_pool.clone()))
.service(health)
.service(post_graphql)
})
.bind(("0.0.0.0", 12155))?
.run()
.await
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment