Skip to content

Revamp Tide, dropping Extractors and simplifying the framework #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 10, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,11 @@ version = "0.0.5"
[dependencies]
cookie = "0.11"
futures-preview = "0.3.0-alpha.13"
fnv = "1.0.6"
http = "0.1"
http-service = "0.1.4"
path-table = "1.0.0"
pin-utils = "0.1.0-alpha.4"
route-recognizer = "0.1.12"
serde = "1.0.80"
serde_derive = "1.0.80"
serde_json = "1.0.32"
Expand Down Expand Up @@ -46,3 +47,5 @@ basic-cookies = "0.1.3"
juniper = "0.10.0"
structopt = "0.2.14"
http-service-mock = "0.1.0"
serde = "1.0.80"
serde_derive = "1.0.80"
53 changes: 24 additions & 29 deletions examples/body_types.rs
Original file line number Diff line number Diff line change
@@ -1,56 +1,51 @@
#![feature(async_await, futures_api)]
#![feature(async_await, futures_api, await_macro)]

#[macro_use]
extern crate serde_derive;
use tide::body;

use tide::{
error::ResultExt,
forms::{self, ExtractForms},
response, App, Context, EndpointResult,
};

#[derive(Serialize, Deserialize, Clone, Debug)]
struct Message {
author: Option<String>,
contents: String,
}

async fn echo_string(msg: body::Str) -> String {
println!("String: {}", *msg);
format!("{}", *msg)
}

async fn echo_string_lossy(msg: body::StrLossy) -> String {
println!("String: {}", *msg);
format!("{}", *msg)
}

async fn echo_vec(msg: body::Bytes) -> Vec<u8> {
println!("Vec<u8>: {:?}", *msg);
msg.to_vec()
}

async fn echo_bytes(msg: body::Bytes) -> body::Bytes {
println!("Bytes: {:?}", *msg);
async fn echo_string(mut cx: Context<()>) -> String {
let msg = await!(cx.body_string()).unwrap();
println!("String: {}", msg);
msg
}

async fn echo_json(msg: body::Json<Message>) -> body::Json<Message> {
println!("JSON: {:?}", *msg);

async fn echo_bytes(mut cx: Context<()>) -> Vec<u8> {
let msg = await!(cx.body_bytes()).unwrap();
println!("Bytes: {:?}", msg);
msg
}

async fn echo_form(msg: body::Form<Message>) -> body::Form<Message> {
println!("Form: {:?}", *msg);
async fn echo_json(mut cx: Context<()>) -> EndpointResult {
let msg = await!(cx.body_json()).client_err()?;
println!("JSON: {:?}", msg);
Ok(response::json(msg))
}

msg
async fn echo_form(mut cx: Context<()>) -> EndpointResult {
let msg = await!(cx.body_form())?;
println!("Form: {:?}", msg);
Ok(forms::form(msg))
}

fn main() {
let mut app = tide::App::new(());
let mut app = App::new(());

app.at("/echo/string").post(echo_string);
app.at("/echo/string_lossy").post(echo_string_lossy);
app.at("/echo/vec").post(echo_vec);
app.at("/echo/bytes").post(echo_bytes);
app.at("/echo/json").post(echo_json);
app.at("/echo/form").post(echo_form);

app.serve();
app.serve("127.0.0.1:8000").unwrap();
}
14 changes: 7 additions & 7 deletions examples/catch_all.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#![feature(async_await, futures_api)]

async fn echo_path(path: tide::head::Path<String>) -> String {
format!("Your path is: {}", *path)
use tide::Context;

async fn echo_path(cx: Context<()>) -> String {
let path: String = cx.param("path").unwrap();
format!("Your path is: {}", path)
}

fn main() {
let mut app = tide::App::new(());
app.at("/echo_path").nest(|router| {
router.at("*").get(echo_path);
});

app.serve();
app.at("/echo_path/:path*").get(echo_path);
app.serve("127.0.0.1:8000").unwrap();
}
48 changes: 0 additions & 48 deletions examples/cli_parsing.rs

This file was deleted.

38 changes: 0 additions & 38 deletions examples/computed_values.rs

This file was deleted.

34 changes: 0 additions & 34 deletions examples/configuration.rs

This file was deleted.

11 changes: 4 additions & 7 deletions examples/cookie_extractor.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
#![feature(async_await, futures_api)]

use tide::Cookies;
use tide::{cookies::ExtractCookies, Context};

/// Tide will use the the `Cookies`'s `Extract` implementation to build this parameter.
///
async fn hello_cookies(cookies: Cookies) -> String {
format!("hello cookies: {:?}", cookies)
async fn hello_cookies(mut cx: Context<()>) -> String {
format!("hello cookies: {:?}", cx.cookie("hello"))
}

fn main() {
let mut app = tide::App::new(());
app.at("/").get(hello_cookies);

let address = "127.0.0.1:8000".to_owned();
println!("Server is listening on http://{}", address);
app.serve();
app.serve("127.0.0.1:8000").unwrap();
}
13 changes: 0 additions & 13 deletions examples/default_handler.rs

This file was deleted.

4 changes: 2 additions & 2 deletions examples/default_headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ fn main() {
.header("X-Server", "Tide"),
);

app.at("/").get(async || "Hello, world!");
app.at("/").get(async move |_| "Hello, world!");

app.serve();
app.serve("127.0.0.1:8000").unwrap();
}
32 changes: 15 additions & 17 deletions examples/graphql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@
//
// [the Juniper book]: https://graphql-rust.github.io/

#![feature(async_await, futures_api)]
#![feature(async_await, futures_api, await_macro)]

use http::status::StatusCode;
use juniper::graphql_object;
use std::sync::{atomic, Arc};
use tide::{body, App, AppData, IntoResponse, Response};
use tide::{error::ResultExt, response, App, Context, EndpointResult};

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

app_data is already Arc<AppData>, do we still need Arc here?


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

// 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: Context |&self| {
graphql_object!(Query: Data |&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 @@ -33,7 +33,7 @@ graphql_object!(Query: Context |&self| {
// `Query`, but it provides the way to "mutate" the accumulator state.
struct Mutation;

graphql_object!(Mutation: Context |&self| {
graphql_object!(Mutation: Data |&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 @@ -45,23 +45,21 @@ 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(
ctx: AppData<Context>,
query: body::Json<juniper::http::GraphQLRequest>,
) -> Response {
let response = query.execute(&Schema::new(Query, Mutation), &ctx);
async fn handle_graphql(mut cx: Context<Data>) -> EndpointResult {
let query: juniper::http::GraphQLRequest = await!(cx.body_json()).client_err()?;
let response = query.execute(&Schema::new(Query, Mutation), cx.app_data());
let status = if response.is_ok() {
StatusCode::OK
} else {
StatusCode::BAD_REQUEST
};
body::Json(response).with_status(status).into_response()
let mut resp = response::json(response);
*resp.status_mut() = status;
Ok(resp)
}

fn main() {
let mut app = App::new(Context::default());

let mut app = App::new(Data::default());
app.at("/graphql").post(handle_graphql);

app.serve();
app.serve("127.0.0.1:8000").unwrap();
}
5 changes: 2 additions & 3 deletions examples/hello.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

fn main() {
let mut app = tide::App::new(());
app.at("/").get(async || "Hello, world!");

app.serve();
app.at("/").get(async move |_| "Hello, world!");
app.serve("127.0.0.1:8000").unwrap();
}
Loading