-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.rs
97 lines (85 loc) · 2.48 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
extern crate futures_state_stream;
extern crate pretty_env_logger;
#[allow(unused_extern_crates)]
extern crate serde;
extern crate serde_json;
extern crate shio;
extern crate tokio_postgres as postgres;
extern crate uuid;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate error_chain;
// TODO: Connection pooling
mod errors {
error_chain! {
foreign_links {
PostgresConnect(::postgres::error::ConnectError);
Postgres(::postgres::error::Error);
Json(::serde_json::Error);
}
}
}
use futures_state_stream::StateStream;
use postgres::{Connection, TlsMode};
use shio::prelude::*;
use errors::*;
#[derive(Serialize)]
struct Person {
id: uuid::Uuid,
name: String,
}
const DATABASE_URL: &'static str = "postgres://postgres@localhost/shio_dev_example";
fn index(ctx: Context) -> BoxFuture<Response, Error> {
Connection::connect(DATABASE_URL, TlsMode::None, &ctx.handle())
.from_err::<Error>()
.and_then(|conn| {
conn.batch_execute(
r#"
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE IF NOT EXISTS person (
id UUID PRIMARY KEY DEFAULT uuid_generate_v1mc(),
name TEXT NOT NULL
);
"#,
).from_err()
})
.and_then(|conn| {
conn.prepare("INSERT INTO person (name) VALUES ($1)")
.from_err()
})
.and_then(move |(stmt, conn)| {
let name: &str = &ctx.get::<Parameters>()["name"];
conn.execute(&stmt, &[&name]).from_err()
})
.and_then(|(_, conn)| {
conn.prepare("SELECT id, name FROM person").from_err()
})
.and_then(|(stmt, conn)| {
conn.query(&stmt, &[])
.map(|row| {
Person {
id: row.get("id"),
name: row.get("name"),
}
})
.collect()
.from_err()
})
.and_then(|(results, _)| {
let s = serde_json::to_string(&results)?;
Ok(
Response::build()
.header(http::header::ContentType::json())
.body(s),
)
})
.into_box()
}
fn main() {
pretty_env_logger::init().unwrap();
Shio::default()
.route((Method::GET, "/{name}", index))
.run(":7878")
.unwrap();
}