From e13a5afa0b6c19295c68f3813b0b68dcd95193a4 Mon Sep 17 00:00:00 2001 From: Ziyang Hu Date: Sat, 27 Aug 2022 21:07:32 +0800 Subject: [PATCH] fixing http --- cozohttp/Cargo.toml | 1 + cozohttp/src/main.rs | 48 +++++++++++++++----------------------------- 2 files changed, 17 insertions(+), 32 deletions(-) diff --git a/cozohttp/Cargo.toml b/cozohttp/Cargo.toml index 19f23360..347a8bcf 100644 --- a/cozohttp/Cargo.toml +++ b/cozohttp/Cargo.toml @@ -10,6 +10,7 @@ actix-web = "4.1.0" clap = { version = "3.2.8", features = ["derive"] } actix-cors = "0.6.1" log = "0.4.16" +anyhow = "1.0.62" env_logger = "0.9.0" serde_json = "1.0.81" cozo = { path = ".." } diff --git a/cozohttp/src/main.rs b/cozohttp/src/main.rs index eda58156..273862b2 100644 --- a/cozohttp/src/main.rs +++ b/cozohttp/src/main.rs @@ -2,16 +2,18 @@ use std::fmt::{Debug, Display, Formatter}; use std::path::Path; use actix_cors::Cors; -use actix_web::{App, HttpResponse, HttpServer, post, Responder, web}; +use actix_web::rt::task::spawn_blocking; +use actix_web::{post, web, App, HttpResponse, HttpServer, Responder}; use clap::Parser; use log::info; +use anyhow::anyhow; use cozo::{Db, DbBuilder}; type Result = std::result::Result; struct RespError { - err: cozo::Error, + err: anyhow::Error, } impl Debug for RespError { @@ -58,31 +60,15 @@ struct AppStateWithDb { db: Db, } -#[post("/tx")] -async fn transact( - body: web::Json, - data: web::Data, -) -> Result { - data.db.transact_triples(&body)?; - Ok(HttpResponse::Ok().body("transact")) -} - -#[post("/txa")] -async fn transact_attr( - body: web::Json, - data: web::Data, -) -> Result { - data.db.transact_attributes(&body)?; - Ok(HttpResponse::Ok().body("transact-attr success")) -} - -#[post("/q")] -async fn query( - body: web::Json, - data: web::Data, -) -> Result { - dbg!(&body, &data.db); - Ok(HttpResponse::Ok().body("query")) +#[post("/text-query")] +async fn query(body: web::Bytes, data: web::Data) -> Result { + let text = std::str::from_utf8(&body) + .map_err(|e| anyhow!(e))? + .to_string(); + let db = data.db.new_session()?; + let task = spawn_blocking(move || db.run_script(&text)); + let result = task.await.map_err(|e| anyhow!(e))??; + Ok(HttpResponse::Ok().json(result)) } #[actix_web::main] @@ -114,10 +100,8 @@ async fn main() -> std::io::Result<()> { .app_data(app_state.clone()) .wrap(cors) .service(query) - .service(transact) - .service(transact_attr) }) - .bind(addr)? - .run() - .await + .bind(addr)? + .run() + .await }