如何在Rust和Nickel中为JSON选择查询结果?

时间:2016-02-04 18:18:40

标签: rust nickel

我使用nickel.rs:

router.get("/api/movies", middleware! { |request, response|
    let mut test_movies =
    r#"[
        { "title": "Ironman"},
        { "title": "The Walk"},
        { "title": "Paddington"}
    ]
    "#;
    let json = Json::from_str(test_movies);
    format!("{}", json.unwrap())
});

我想创建JSON格式。连接到PostgreSQL并转换为JSON定义的代码如下:

extern crate rustc_serialize;
use rustc_serialize::json::{Json, Parser};

#[derive(RustcDecodable, RustcEncodable)]
struct Movie {
    title: String,
}

我尝试选择查询并创建JSON

router.get("/api/movies", middleware! { |request, response|
    let conn = Connection::connect("postgres://postgres@localhost", SslMode::None).unwrap();
    let stmt = match conn.prepare("select title from movie") {
        Ok(stmt) => stmt,
        Err(e) => {
            return response.send(format!("Preparing query failed: {}", e));
        }
    };
    let res = match stmt.execute(&[]) {
        Ok(v) => println!("Selecting movie was Success."),
        Err(e) => println!("Selecting movie failed. => {:?}", e)
    };

    // ???
    // let movies = Json::from_obj(res);
    // let movies = request.json_as::<&[Movie]>().unwrap();
    // let movies = request.json_as::Vec<Movie>().unwrap();
    format!("{}", movies)
});

但是,我不知道如何将结果转换为JSON。

let conn = conn.clone();

发生错误。

error: no method named `clone` found for type `postgres::Connection` in the current scope

我添加了

use nickel::status::StatusCode;

//use rustc_serialize::json::{Json, Parser};
use rustc_serialize::{json};

json::encode(&movies).unwrap();

是工作。但null返回...

最后

我将execute更改为query,并使用Vec<Movie>

let mut v: Vec<Movie> = vec![];
let movies = &conn.query("select title from movie", &[]).unwrap();
for row in movies {
    let movie = Movie {
        title: row.get(0),
    };

    v.push(movie);
}

let json_obj = json::encode(&v).unwrap();
response.set(MediaType::Json);
response.set(StatusCode::Ok);
return response.send(json_obj);

我还将struct Moview定义为模型

struct Movie {
    // id: i32,
    title: String,
}
嗯......麻烦很多。

然而,我还不能conn.clone()

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

    let json = json::encode(&res).unwrap();
    response.set(MediaType::Json);
    response.set(StatusCode::Ok);
    return response.send(json);

此外,为每个请求创建新连接效率不高。您可以在main()函数中创建一个连接,然后在每个请求闭包内克隆它。

fn main(){

    let mut server = Nickel::new();
    let mut router = Nickel::router();

    let conn = Connection::connect("postgres://postgres@localhost", SslMode::None).unwrap();
    let shared_connection = Arc::new(conn);


    {
        let conn = shared_connection.clone();
        router.get("/api/movies", middleware! ( |request, mut response|{

            let mut v: Vec<Movie> = vec![];
            let movies = &conn.query("select title", &[]).unwrap();
            for row in movies {
                let movie = Movie {
                    title: row.get(0),
                };

                v.push(movie);
            }

            let json_obj = json::encode(&v).unwrap();
            res.set(MediaType::Json);
            res.set(StatusCode::Ok);
            return res.send(json_obj);

        }));
    }

    {
        let conn = shared_connection.clone();
        router.post("/api/movies",middleware!(|request, mut response|{

            //...

        }));
    }

    server.utilize(router);
    server.listen("127.0.0.1:6767");
}