Browse Source

segments continue

pull/25/head
Alexey Velikiy 3 years ago
parent
commit
6cceb8f744
  1. 16
      server/src/api.rs
  2. 6
      server/src/api/metric.rs
  3. 125
      server/src/api/segments.rs
  4. 4
      server/src/services/data_service.rs

16
server/src/api.rs

@ -2,6 +2,7 @@ use hastic::config::Config;
use hastic::services::{data_service, metric_service, user_service};
use warp::http::HeaderValue;
use warp::hyper::{Body, StatusCode};
use warp::reject::Reject;
use warp::{body, options, Rejection, Reply};
use warp::{http::Response, Filter};
@ -14,6 +15,12 @@ use serde::Serialize;
use parking_lot::RwLock;
use std::sync::Arc;
#[derive(Debug)]
struct BadQuery;
impl Reject for BadQuery {}
#[derive(Serialize)]
pub struct Message {
message: String,
@ -70,12 +77,17 @@ impl API<'_> {
});
let metrics = metric::get_route(self.metric_service.clone());
let login = auth::get_route(self.user_service.clone());
let segments = segments::get_route(self.data_service.clone());
// let segments = segments::get_route(self.data_service.clone());
let public = warp::fs::dir("public");
println!("Start server on {} port", self.config.port);
// TODO: move it to "server"
let routes = login.or(metrics).or(segments).or(options).or(public).or(not_found);
let routes = login
.or(metrics)
//.or(segments)
.or(options)
.or(public)
.or(not_found);
warp::serve(routes).run(([127, 0, 0, 1], self.config.port)).await;
}
}

6
server/src/api/metric.rs

@ -21,15 +21,13 @@ use std::error::Error;
use std::fmt::Debug;
use std::sync::Arc;
use super::BadQuery;
#[derive(Serialize)]
struct QueryResponse {
message: String,
}
#[derive(Debug)]
struct BadQuery;
impl Reject for BadQuery {}
async fn get_query(
p: HashMap<String, String>,

125
server/src/api/segments.rs

@ -1,71 +1,84 @@
use hastic::services::data_service::{self, Segment};
mod filters {
use warp::Filter;
use super::models::{Db, ListOptions};
use super::handlers;
use warp::filters::method::get;
use warp::http::HeaderValue;
use warp::hyper::{Body, StatusCode};
use warp::reject::Reject;
use warp::{http::Response, Filter};
use warp::{Rejection, Reply};
/// The 4 REST API filters combined.
pub fn filters(
db: Db,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
list(db.clone())
.or(create(db.clone()))
// .or(update(db.clone()))
// .or(delete(db.clone()))
}
use serde::Serialize;
/// GET /segments?from=3&to=5
pub fn list(
db: Db,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("segments")
.and(warp::get())
.and(warp::query::<ListOptions>())
.and(with_db(db))
.and_then(handlers::list)
}
use crate::api::{self, API};
/// POST /segments with JSON body
pub fn create(
db: Db
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
warp::path!("segments")
.and(warp::post())
.and(warp::body::json())
.and(with_db(db))
.and_then(handlers::create)
}
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
fn with_db(db: Db) -> impl Filter<Extract = (Db,), Error = std::convert::Infallible> + Clone {
warp::any().map(move || db.clone())
}
#[derive(Serialize)]
struct SegmentsResult {
segments: Vec<Segment>
}
#[derive(Debug)]
struct BadQuery;
impl Reject for BadQuery {}
mod handlers {
use hastic::services::data_service;
use crate::api::API;
use crate::api::BadQuery;
use super::models::ListOptions;
use super::models::Db;
async fn get_query(
p: HashMap<String, String>,
ds: Arc<RwLock<data_service::DataService>>,
) -> anyhow::Result<SegmentsResult> {
if !p.contains_key("from") {
return Err(anyhow::anyhow!("Missing attribute from"));
pub async fn list(opts: ListOptions, db: Db) -> Result<impl warp::Reply, warp::Rejection> {
// Just return a JSON array of todos, applying the limit and offset.
match db.read().get_segments(opts.from, opts.to) {
Ok(segments) => Ok(API::json(&segments)),
Err(e) => Err(warp::reject::custom(BadQuery))
}
}
if !p.contains_key("to") {
return Err(anyhow::anyhow!("Missing attribute to"));
pub async fn create(segment: data_service::Segment, db: Db) -> Result<impl warp::Reply, warp::Rejection> {
// Just return a JSON array of todos, applying the limit and offset.
match db.write().insert_segment(&segment) {
Ok(segments) => Ok(API::json(&segments)),
Err(e) => Err(warp::reject::custom(BadQuery))
}
}
let from = p.get("from").unwrap().parse::<u64>()?;
let to = p.get("to").unwrap().parse::<u64>()?;
}
let res = ds.read().get_segments(from, to)?;
drop(ds);
mod models {
use serde::{Deserialize};
use hastic::services::data_service;
use parking_lot::RwLock;
use std::sync::Arc;
Ok(SegmentsResult{ segments: res })
// Ok(prom.query(from, to, step).await?)
}
pub type Db = Arc<RwLock<data_service::DataService>>;
async fn query(
p: HashMap<String, String>,
ds: Arc<RwLock<data_service::DataService>>,
) -> Result<impl warp::Reply, warp::Rejection> {
//Err(warp::reject::custom(BadQuery));
match get_query(p, ds).await {
Ok(res) => Ok(API::json(&res)),
// TODO: parse different error types
Err(_e) => Err(warp::reject::custom(BadQuery)),
// The query parameters for list_todos.
#[derive(Debug, Deserialize)]
pub struct ListOptions {
pub from: u64,
pub to: u64,
}
}
pub fn get_route(
data_service: Arc<RwLock<data_service::DataService>>,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
return warp::path!("api" / "segments")
.and(get())
.and(warp::query::<HashMap<String, String>>())
.and(warp::any().map(move || data_service.clone()))
.and_then(query);
}
}

4
server/src/services/data_service.rs

@ -1,11 +1,11 @@
use rusqlite::{ Connection, params };
use serde::Serialize;
use serde::{Serialize, Deserialize};
use std::sync::{Arc, Mutex};
#[derive(Debug, Serialize)]
#[derive(Debug, Serialize, Deserialize)]
pub struct Segment {
pub id: Option<u64>,
pub start: u64,

Loading…
Cancel
Save