roa-pg

Crates.ioroa-pg
lib.rsroa-pg
version0.5.1
sourcesrc
created_at2020-03-28 08:13:02.564712
updated_at2020-04-06 19:20:48.503125
descriptiontokio-postgres integration with roa framework
homepagehttps://github.com/Hexilee/roa/wiki
repositoryhttps://github.com/Hexilee/roa
max_upload_size
id223749
size14,008
xixi (Hexilee)

documentation

https://docs.rs/roa-pg

README

Stable Test codecov Rust Docs Crate version Download Version License: MIT

This crate provides integration with tokio-postgres.

Example

use roa::{App, Context, throw};
use roa::http::StatusCode;
use roa_pg::{connect, Client};
use std::sync::Arc;
use std::error::Error;
use roa::query::query_parser;
use roa::preload::*;
use async_std::task::spawn;

#[derive(Clone)]
struct State {
    pg: Arc<Client>
}

impl State {
    pub async fn new(pg_url: &str) -> Result<Self, Box<dyn Error>> {
        let (client, conn) = connect(&pg_url.parse()?).await?;
        spawn(conn);
        Ok(Self {pg: Arc::new(client)})
    }
}

async fn query(ctx: &mut Context<State>) -> roa::Result {
    let id: u32 = ctx.must_query("id")?.parse()?;
    match ctx.pg.query_opt("SELECT * FROM user WHERE id=$1", &[&id]).await? {
        Some(row) => {
            let value: String = row.get(0);
            ctx.write(value);
            Ok(())
        }
        None => throw!(StatusCode::NOT_FOUND),
    }
}

#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let url = "postgres://fred:secret@localhost/test";
    let state = State::new(url).await?;
    App::new(state)
        .gate(query_parser)
        .end(query)
        .listen("127.0.0.1:0", |addr| {
            println!("Server is listening on {}", addr)
        })?.await?;
    Ok(())
}
Commit count: 722

cargo fmt