Skip to content

Commit

Permalink
rename Data to State #260
Browse files Browse the repository at this point in the history
Signed-off-by: Yoshua Wuyts <yoshuawuyts@gmail.com>
  • Loading branch information
yoshuawuyts committed Nov 3, 2019
1 parent bb614a9 commit 7ece9c1
Show file tree
Hide file tree
Showing 9 changed files with 37 additions and 34 deletions.
14 changes: 7 additions & 7 deletions examples/graphql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ use juniper::graphql_object;
use std::sync::{atomic, Arc};
use tide::{error::ResultExt, response, App, Context, EndpointResult};

// First, we define `Data` that holds accumulator state. This is accessible as App data in
// First, we define `State` that holds accumulator state. This is accessible as App data in
// Tide, and as executor context in Juniper.
#[derive(Clone, Default)]
struct Data(Arc<atomic::AtomicIsize>);
struct State(Arc<atomic::AtomicIsize>);

impl juniper::Context for Data {}
impl juniper::Context for State {}

// We define `Query` unit struct here. GraphQL queries will refer to this struct. The struct itself
// doesn't have any associated data (and there's no need to do so), but instead it exposes the
// accumulator state from the context.
struct Query;

graphql_object!(Query: Data |&self| {
graphql_object!(Query: State |&self| {
// GraphQL integers are signed and 32 bits long.
field accumulator(&executor) -> i32 as "Current value of the accumulator" {
executor.context().0.load(atomic::Ordering::Relaxed) as i32
Expand All @@ -31,7 +31,7 @@ graphql_object!(Query: Data |&self| {
// `Query`, but it provides the way to "mutate" the accumulator state.
struct Mutation;

graphql_object!(Mutation: Data |&self| {
graphql_object!(Mutation: State |&self| {
field add(&executor, by: i32) -> i32 as "Add given value to the accumulator." {
executor.context().0.fetch_add(by as isize, atomic::Ordering::Relaxed) as i32 + by
}
Expand All @@ -43,7 +43,7 @@ type Schema = juniper::RootNode<'static, Query, Mutation>;

// Finally, we'll bridge between Tide and Juniper. `GraphQLRequest` from Juniper implements
// `Deserialize`, so we use `Json` extractor to deserialize the request body.
async fn handle_graphql(mut cx: Context<Data>) -> EndpointResult {
async fn handle_graphql(mut cx: Context<State>) -> EndpointResult {
let query: juniper::http::GraphQLRequest = cx.body_json().await.client_err()?;
let schema = Schema::new(Query, Mutation);
let response = query.execute(&schema, cx.state());
Expand All @@ -58,7 +58,7 @@ async fn handle_graphql(mut cx: Context<Data>) -> EndpointResult {
}

fn main() {
let mut app = App::with_state(Data::default());
let mut app = App::with_state(State::default());
app.at("/graphql").post(handle_graphql);
app.serve("127.0.0.1:8000").unwrap();
}
20 changes: 10 additions & 10 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ use crate::{
pub struct App<State> {
router: Router<State>,
middleware: Vec<Arc<dyn Middleware<State>>>,
data: State,
state: State,
}

impl App<()> {
Expand All @@ -149,7 +149,7 @@ impl<State: Send + Sync + 'static> App<State> {
App {
router: Router::new(),
middleware: Vec::new(),
data: state,
state,
}
}

Expand Down Expand Up @@ -225,7 +225,7 @@ impl<State: Send + Sync + 'static> App<State> {
pub fn into_http_service(self) -> Server<State> {
Server {
router: Arc::new(self.router),
data: Arc::new(self.data),
state: Arc::new(self.state),
middleware: Arc::new(self.middleware),
}
}
Expand Down Expand Up @@ -254,7 +254,7 @@ impl<State: Send + Sync + 'static> App<State> {
#[allow(missing_debug_implementations)]
pub struct Server<State> {
router: Arc<Router<State>>,
data: Arc<State>,
state: Arc<State>,
middleware: Arc<Vec<Arc<dyn Middleware<State>>>>,
}

Expand All @@ -272,12 +272,12 @@ impl<State: Sync + Send + 'static> HttpService for Server<State> {
let method = req.method().to_owned();
let router = self.router.clone();
let middleware = self.middleware.clone();
let data = self.data.clone();
let state = self.state.clone();

Box::pin(async move {
let fut = {
let Selection { endpoint, params } = router.route(&path, method);
let cx = Context::new(data, req, params);
let cx = Context::new(state, req, params);

let next = Next {
endpoint,
Expand All @@ -300,19 +300,19 @@ mod tests {
use super::*;
use crate::{middleware::Next, router::Selection, Context, Response};

fn simulate_request<'a, Data: Default + Clone + Send + Sync + 'static>(
app: &'a App<Data>,
fn simulate_request<'a, State: Default + Clone + Send + Sync + 'static>(
app: &'a App<State>,
path: &'a str,
method: http::Method,
) -> BoxFuture<'a, Response> {
let Selection { endpoint, params } = app.router.route(path, method.clone());

let data = Arc::new(Data::default());
let state = Arc::new(State::default());
let req = http::Request::builder()
.method(method)
.body(http_service::Body::empty())
.unwrap();
let cx = Context::new(data, req, params);
let cx = Context::new(state, req, params);
let next = Next {
endpoint,
next_middleware: &app.middleware,
Expand Down
4 changes: 2 additions & 2 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use http_service::Body;
use route_recognizer::Params;
use std::{str::FromStr, sync::Arc};

/// Data associated with a request-response lifecycle.
/// State associated with a request-response lifecycle.
///
/// The `Context` gives endpoints access to basic information about the incoming
/// request, route parameters, and various ways of accessing the request's body.
Expand Down Expand Up @@ -55,7 +55,7 @@ impl<State> Context<State> {
&self.request
}

/// Access app-global data.
/// Access app-global state.
pub fn state(&self) -> &State {
&self.state
}
Expand Down
6 changes: 3 additions & 3 deletions src/middleware/cookies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ impl CookiesMiddleware {
}
}

impl<Data: Send + Sync + 'static> Middleware<Data> for CookiesMiddleware {
impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
fn handle<'a>(
&'a self,
mut cx: Context<Data>,
next: Next<'a, Data>,
mut cx: Context<State>,
next: Next<'a, State>,
) -> BoxFuture<'a, Response> {
Box::pin(async move {
let cookie_data = cx
Expand Down
4 changes: 2 additions & 2 deletions src/middleware/default_headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ impl DefaultHeaders {
}
}

impl<Data: Send + Sync + 'static> Middleware<Data> for DefaultHeaders {
fn handle<'a>(&'a self, cx: Context<Data>, next: Next<'a, Data>) -> BoxFuture<'a, Response> {
impl<State: Send + Sync + 'static> Middleware<State> for DefaultHeaders {
fn handle<'a>(&'a self, cx: Context<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
Box::pin(async move {
let mut res = next.run(cx).await;

Expand Down
10 changes: 5 additions & 5 deletions src/middleware/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ impl RequestLogger {
Self::default()
}

async fn log_basic<'a, Data: Send + Sync + 'static>(
async fn log_basic<'a, State: Send + Sync + 'static>(
&'a self,
ctx: Context<Data>,
next: Next<'a, Data>,
ctx: Context<State>,
next: Next<'a, State>,
) -> Response {
let path = ctx.uri().path().to_owned();
let method = ctx.method().as_str().to_owned();
Expand All @@ -43,8 +43,8 @@ impl RequestLogger {
}
}

impl<Data: Send + Sync + 'static> Middleware<Data> for RequestLogger {
fn handle<'a>(&'a self, ctx: Context<Data>, next: Next<'a, Data>) -> BoxFuture<'a, Response> {
impl<State: Send + Sync + 'static> Middleware<State> for RequestLogger {
fn handle<'a>(&'a self, ctx: Context<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
Box::pin(async move { self.log_basic(ctx, next).await })
}
}
9 changes: 6 additions & 3 deletions src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ pub trait Middleware<State>: 'static + Send + Sync {
fn handle<'a>(&'a self, cx: Context<State>, next: Next<'a, State>) -> BoxFuture<'a, Response>;
}

impl<Data, F> Middleware<Data> for F
impl<State, F> Middleware<State> for F
where
F: Send + Sync + 'static + for<'a> Fn(Context<Data>, Next<'a, Data>) -> BoxFuture<'a, Response>,
F: Send
+ Sync
+ 'static
+ for<'a> Fn(Context<State>, Next<'a, State>) -> BoxFuture<'a, Response>,
{
fn handle<'a>(&'a self, cx: Context<Data>, next: Next<'a, Data>) -> BoxFuture<'a, Response> {
fn handle<'a>(&'a self, cx: Context<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
(self)(cx, next)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/querystring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub trait ContextExt<'de> {
fn url_query<T: Deserialize<'de>>(&'de self) -> Result<T, Error>;
}

impl<'de, Data> ContextExt<'de> for Context<Data> {
impl<'de, State> ContextExt<'de> for Context<State> {
#[inline]
fn url_query<T: Deserialize<'de>>(&'de self) -> Result<T, Error> {
let query = self.uri().query();
Expand Down
2 changes: 1 addition & 1 deletion src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ impl<State: 'static> Router<State> {
}
}

fn not_found_endpoint<Data>(_cx: Context<Data>) -> BoxFuture<'static, Response> {
fn not_found_endpoint<State>(_cx: Context<State>) -> BoxFuture<'static, Response> {
Box::pin(async move {
http::Response::builder()
.status(http::StatusCode::NOT_FOUND)
Expand Down

0 comments on commit 7ece9c1

Please sign in to comment.