juniper icon indicating copy to clipboard operation
juniper copied to clipboard

Accessing data from the request for juniper_hyper

Open derust opened this issue 5 years ago • 1 comments

I'm new to rust, and try to start play with juniper, the experience is really nice, thank for your great job.

I'm currently use juniper_hyper since juniper_iron seems not support async resolve.

My problem is: I can't find a way to get the client's ip in graphql resolve, which juniper_iron can easily achieve. https://graphql-rust.github.io/juniper/master/servers/iron.html#accessing-data-from-the-request

Is there any way for juniper_hyper to accessing data from the request like juniper_iron?

Thanks

derust avatar Apr 25 '20 15:04 derust

I just ran some tests and this is possible. Here is small example. Notice that this example requires the newest changes on the master (includes subscription support!). I marked the interesting lines which provides the address and are different from the provided hyper example (in the master branch). It should be no problem porting this to stable.

#![deny(warnings)]

use hyper::{
    service::{make_service_fn, service_fn},
    Body, Method, Response, Server, StatusCode,
    server::conn::AddrStream
};
use juniper::{EmptyMutation, EmptySubscription, RootNode};
use std::sync::Arc;

type Schema = RootNode<'static, Query, EmptyMutation<Ctx>, EmptySubscription<Ctx>>;

pub struct Query;

#[juniper::graphql_object(Context = Ctx)]
impl Query {
    fn test(&self, ctx: &Ctx) -> String {
        ctx.addr.to_string()
    }
}

fn schema() -> Schema {
    Schema::new(
        Query,
        EmptyMutation::<Ctx>::new(),
        EmptySubscription::<Ctx>::new(),
    )
}
#[derive(Clone)]
pub struct Ctx {
    db: Arc<Database>,
    addr: std::net::SocketAddr,
}

pub struct Database {}

impl Database {
    pub fn new() -> Self {
        Self {}
    }
}

#[tokio::main]
async fn main() {
    let addr = ([127, 0, 0, 1], 3000).into();
    let db = Arc::new(Database::new());

    let root_node: Arc<Schema> = Arc::new(schema());

    let new_service = make_service_fn(move |socket: &AddrStream| { // here
        let root_node = root_node.clone();
        let ctx = Arc::new(Ctx {
            db: db.clone(),
            addr: socket.remote_addr(), // read address
        });

        async move {
            Ok::<_, hyper::Error>(service_fn(move |req| {
                let root_node = root_node.clone();
                let ctx = ctx.clone();
                async move {
                    match (req.method(), req.uri().path()) {
                        (&Method::GET, "/") => juniper_hyper::graphiql("/graphql", None).await,
                        (&Method::GET, "/graphql") | (&Method::POST, "/graphql") => {
                            juniper_hyper::graphql(root_node, ctx, req).await
                        }
                        _ => {
                            let mut response = Response::new(Body::empty());
                            *response.status_mut() = StatusCode::NOT_FOUND;
                            Ok(response)
                        }
                    }
                }
            }))
        }
    });

    let server = Server::bind(&addr).serve(new_service);
    println!("Listening on http://{}", addr);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e)
    }
}

jmpunkt avatar May 06 '20 21:05 jmpunkt