Skip to content

Commit

Permalink
Torii graphql add cors argument
Browse files Browse the repository at this point in the history
  • Loading branch information
broody committed Oct 4, 2023
1 parent d4f36a2 commit 2bcb6d6
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
11 changes: 5 additions & 6 deletions crates/torii/graphql/src/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,16 @@ pub async fn filter(
pool: &Pool<Sqlite>,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
let schema = build_schema(pool).await.unwrap();
let graphql_filter = warp::path("graphql")
.and(warp::post())
.and(async_graphql_warp::graphql(schema))
.and_then(|(schema, request): (Schema, async_graphql::Request)| async move {
let graphql_filter = warp::path("graphql").and(async_graphql_warp::graphql(schema)).and_then(
|(schema, request): (Schema, async_graphql::Request)| async move {
// Execute query
let response = schema.execute(request).await;
// Return result
Ok::<_, Infallible>(warp::reply::json(&response))
});
},
);

let graphiql_filter = warp::path("graphql").and(warp::get()).map(|| {
let graphiql_filter = warp::path("graphql").map(|| {
warp::reply::html(playground_source(
GraphQLPlaygroundConfig::new("/graphql").subscription_endpoint("/graphql/ws"),
))
Expand Down
7 changes: 6 additions & 1 deletion crates/torii/server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ struct Args {
/// Port number for api endpoints
#[arg(long, default_value = "8080")]
port: u16,
/// Specify allowed origins for api endpoints (comma-separated list of allowed origins, or "*" for
/// all)
#[arg(long, default_value = "*")]
#[arg(value_delimiter = ',')]
allowed_origins: Vec<String>,
}

#[tokio::main]
Expand Down Expand Up @@ -104,7 +109,7 @@ async fn main() -> anyhow::Result<()> {
}
}

res = server::spawn_server(&addr, &pool, args.world_address, block_receiver, Arc::clone(&provider)) => {
res = server::spawn_server(&addr, &pool, args.world_address, block_receiver, Arc::clone(&provider), args.allowed_origins) => {
if let Err(e) = res {
error!("Server failed with error: {e}");
}
Expand Down
27 changes: 23 additions & 4 deletions crates/torii/server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use std::sync::Arc;
use std::task::Poll;

use either::Either;
use http::header::{ACCEPT, ACCESS_CONTROL_ALLOW_ORIGIN, CONTENT_TYPE, ORIGIN};
use http::Method;
use hyper::service::{make_service_fn, Service};
use hyper::Uri;
use sqlx::{Pool, Sqlite};
Expand All @@ -14,6 +16,7 @@ use starknet::providers::JsonRpcClient;
use starknet_crypto::FieldElement;
use tokio::sync::mpsc::Receiver as BoundedReceiver;
use torii_grpc::protos;
use warp::filters::cors::Builder;
use warp::Filter;

type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
Expand All @@ -25,16 +28,21 @@ pub async fn spawn_server(
world_address: FieldElement,
block_receiver: BoundedReceiver<u64>,
provider: Arc<JsonRpcClient<HttpTransport>>,
allowed_origins: Vec<String>,
) -> anyhow::Result<()> {
let world_server =
torii_grpc::server::DojoWorld::new(pool.clone(), block_receiver, world_address, provider);

let base_route = warp::path::end()
.and(warp::get())
.map(|| warp::reply::json(&serde_json::json!({ "success": true })));
let routes = torii_graphql::route::filter(pool).await.or(base_route);
let base_route =
warp::path::end().map(|| warp::reply::json(&serde_json::json!({ "success": true })));
let routes = torii_graphql::route::filter(pool)
.await
.or(base_route)
.with(configure_cors(&allowed_origins));

let warp = warp::service(routes);

// TODO: apply allowed_origins to tonic grpc
let tonic = tonic_web::enable(protos::world::world_server::WorldServer::new(world_server));

hyper::Server::bind(addr)
Expand Down Expand Up @@ -81,6 +89,17 @@ pub async fn spawn_server(
Ok(())
}

fn configure_cors(origins: &Vec<String>) -> Builder {
if origins.len() == 1 && origins[0] == "*" {
warp::cors().allow_any_origin()
} else {
let origins_str: Vec<&str> = origins.iter().map(|origin| origin.as_str()).collect();
warp::cors().allow_origins(origins_str)
}
.allow_headers(vec![ACCEPT, ORIGIN, CONTENT_TYPE, ACCESS_CONTROL_ALLOW_ORIGIN])
.allow_methods(&[Method::POST, Method::GET, Method::OPTIONS])
}

enum EitherBody<A, B> {
Left(A),
Right(B),
Expand Down

0 comments on commit 2bcb6d6

Please sign in to comment.