2022-02-22 14:16:50 +00:00
|
|
|
use crate::err::Error;
|
2022-02-09 15:55:04 +00:00
|
|
|
use crate::net::head;
|
|
|
|
use crate::net::output;
|
2022-05-10 07:29:25 +00:00
|
|
|
use crate::net::session;
|
2022-02-17 07:39:40 +00:00
|
|
|
use crate::net::DB;
|
2022-01-13 17:36:41 +00:00
|
|
|
use bytes::Bytes;
|
2020-06-29 15:36:01 +00:00
|
|
|
use futures::{FutureExt, StreamExt};
|
2022-02-22 14:16:50 +00:00
|
|
|
use surrealdb::Session;
|
2020-06-29 15:36:01 +00:00
|
|
|
use warp::Filter;
|
|
|
|
|
2022-05-10 00:07:03 +00:00
|
|
|
const MAX: u64 = 1024 * 1024; // 1 MiB
|
|
|
|
|
2020-06-29 15:36:01 +00:00
|
|
|
pub fn config() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
|
|
|
|
// Set base path
|
|
|
|
let base = warp::path("sql").and(warp::path::end());
|
|
|
|
// Set opts method
|
|
|
|
let opts = base.and(warp::options()).map(warp::reply);
|
|
|
|
// Set post method
|
|
|
|
let post = base
|
|
|
|
.and(warp::post())
|
2022-05-10 07:29:25 +00:00
|
|
|
.and(session::build())
|
2020-06-29 15:36:01 +00:00
|
|
|
.and(warp::header::<String>(http::header::CONTENT_TYPE.as_str()))
|
2022-05-10 00:07:03 +00:00
|
|
|
.and(warp::body::content_length_limit(MAX))
|
2021-03-29 15:43:37 +00:00
|
|
|
.and(warp::body::bytes())
|
2020-06-29 15:36:01 +00:00
|
|
|
.and_then(handler);
|
|
|
|
// Set sock method
|
|
|
|
let sock = base.and(warp::ws()).map(|ws: warp::ws::Ws| {
|
|
|
|
ws.on_upgrade(|websocket| {
|
|
|
|
// Just echo all messages back...
|
|
|
|
let (tx, rx) = websocket.split();
|
|
|
|
rx.forward(tx).map(|result| {
|
|
|
|
if let Err(e) = result {
|
|
|
|
eprintln!("websocket error: {:?}", e);
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
});
|
|
|
|
// Specify route
|
|
|
|
opts.or(post).or(sock).with(head::cors())
|
|
|
|
}
|
|
|
|
|
2022-01-13 17:36:41 +00:00
|
|
|
async fn handler(
|
|
|
|
session: Session,
|
|
|
|
output: String,
|
|
|
|
sql: Bytes,
|
|
|
|
) -> Result<impl warp::Reply, warp::Rejection> {
|
2022-05-03 20:20:36 +00:00
|
|
|
let db = DB.get().unwrap();
|
2021-03-29 15:43:37 +00:00
|
|
|
let sql = std::str::from_utf8(&sql).unwrap();
|
2022-05-03 20:20:36 +00:00
|
|
|
match db.execute(sql, &session, None).await {
|
2022-01-14 17:13:44 +00:00
|
|
|
Ok(res) => match output.as_ref() {
|
2022-02-05 23:06:16 +00:00
|
|
|
"application/json" => Ok(output::json(&res)),
|
|
|
|
"application/cbor" => Ok(output::cbor(&res)),
|
|
|
|
"application/msgpack" => Ok(output::pack(&res)),
|
2022-01-14 17:13:44 +00:00
|
|
|
_ => Err(warp::reject::not_found()),
|
|
|
|
},
|
2022-02-22 14:16:50 +00:00
|
|
|
Err(err) => Err(warp::reject::custom(Error::from(err))),
|
2020-06-29 15:36:01 +00:00
|
|
|
}
|
|
|
|
}
|