Add small tide example

This commit is contained in:
Ryan Leckey 2019-11-21 23:29:40 +00:00
parent f02b01dcb6
commit e47e90ec75
4 changed files with 96 additions and 0 deletions

3
.gitignore vendored
View File

@ -9,3 +9,6 @@ Cargo.lock
.idea/
*.vim
*.vi
# Environment
.env

View File

@ -1,3 +1,10 @@
[workspace]
members = [
".",
"sqlx-macros",
"examples/tide"
]
[package]
name = "sqlx"
version = "0.1.1-pre"

15
examples/tide/Cargo.toml Normal file
View File

@ -0,0 +1,15 @@
[package]
name = "sqlx-example-tide"
version = "0.1.0"
edition = "2018"
workspace = "../.."
[dependencies]
anyhow = "1.0.22"
dotenv = "0.15.0"
# async-std = "1.1.0"
# tide = { git = "https://github.com/http-rs/tide", rev = "eb57bcb2ba07a77c91ad3952ca0a0143b03009bc" }
tide = "0.3.0"
tokio = { version = "0.2.0-alpha.4", default-features = false, features = [ "rt-full" ] }
sqlx = { path = "../..", features = [ "postgres" ] }
serde = { version = "1", features = [ "derive"] }

71
examples/tide/src/main.rs Normal file
View File

@ -0,0 +1,71 @@
use sqlx::{Pool, Postgres};
use std::env;
use tide::error::ResultExt;
use tide::response;
use tide::EndpointResult;
use tide::http::StatusCode;
use tide::{App, Context};
// #[async_std::main]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenv::dotenv()?;
let pool = Pool::<Postgres>::new(&env::var("DATABASE_URL")?).await?;
run_migrations(&pool).await?;
let mut app = App::with_state(pool);
app.at("/v1/user").get(get_all_users).post(create_user);
app.serve(("localhost", 8080))?;
Ok(())
}
async fn run_migrations(mut pool: &Pool<Postgres>) -> anyhow::Result<()> {
let _ = sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS users (
id INT GENERATED ALWAYS AS IDENTITY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
name TEXT NOT NULL
);
"#,
)
.execute(&mut pool)
.await?;
Ok(())
}
async fn get_all_users(cx: Context<Pool<Postgres>>) -> EndpointResult {
let mut pool = cx.state();
let users: Vec<(i32, String)> = sqlx::query(r#"SELECT id, name FROM users"#)
.fetch_all(&mut pool)
.await
.server_err()?;
Ok(response::json(users))
}
#[derive(serde::Deserialize)]
struct CreateUserRequest {
name: String,
}
async fn create_user(mut cx: Context<Pool<Postgres>>) -> EndpointResult<StatusCode> {
let req_body: CreateUserRequest = cx.body_json().await.client_err()?;
let mut pool = cx.state();
let _ = sqlx::query(r#"INSERT INTO users ( name ) VALUES ( $1 )"#)
.bind(req_body.name)
.execute(&mut pool)
.await
.server_err()?;
Ok(StatusCode::CREATED)
}