Skip to content

Commit

Permalink
Merge pull request #8 from woodgern/add-metric-query-endpoint
Browse files Browse the repository at this point in the history
Add metric query endpoint

query by combination of offset, start_datetime, end_datetime
  • Loading branch information
Kaiser Dandangi authored Nov 14, 2019
2 parents 8fbcba4 + 3540c46 commit 1255c02
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 5 deletions.
74 changes: 72 additions & 2 deletions metrix/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ use lib::establish_connection;
use schema::metrics;
use models::*;
use rocket_contrib::json::Json;
use rocket::http::RawStr;
use chrono::naive::NaiveDateTime;
use diesel::sql_query;


#[get("/")]
fn ping() -> &'static str {
"pong"
}


#[post("/", data = "<metric_body>")]
fn create_metric_route(metric_body: Json<NewMetric>) -> Json<Metric> {
let new_metric: NewMetric = metric_body.into_inner();
Expand All @@ -41,6 +44,73 @@ fn create_metric_route(metric_body: Json<NewMetric>) -> Json<Metric> {
Json(result)
}

#[get("/?<offset>&<start_datetime>&<end_datetime>")]
fn query_metric_route(
offset: Option<&RawStr>,
start_datetime: Option<&RawStr>,
end_datetime: Option<&RawStr>,
) -> Json<Vec<Metric>> {
let db_conn = establish_connection();
let mut filter_clause = String::from("WHERE 1=1");

if offset.is_some() {
let result = offset.unwrap().url_decode();
// https://api.rocket.rs/v0.3/rocket/http/struct.RawStr.html
if result.is_ok() {
let metric_id_str: String = result.ok().unwrap();
filter_clause.insert_str(
filter_clause.len(),
&format!(" AND id > {}", metric_id_str).to_string()
);
}
}

if start_datetime.is_some() {
let result = start_datetime.unwrap().url_decode();
if result.is_ok() {
let created_at_start = result.ok().unwrap();
let created_at_start_parsed = NaiveDateTime::parse_from_str(
&created_at_start,
&"%Y-%m-%dT%H:%M:%S".to_string() // "2014-5-17T12:34:56"
);

if created_at_start_parsed.is_ok() {
filter_clause.insert_str(
filter_clause.len(),
&format!(" AND created_at >= '{}'", created_at_start).to_string()
);
}
}
}

if end_datetime.is_some() {
let result = end_datetime.unwrap().url_decode();
if result.is_ok() {
let created_at_end = result.ok().unwrap();
let created_at_end_parsed = NaiveDateTime::parse_from_str(
&created_at_end,
&"%Y-%m-%dT%H:%M:%S".to_string() // "2014-5-17T12:34:56"
);

if created_at_end_parsed.is_ok() {
filter_clause.insert_str(
filter_clause.len(),
&format!(" AND created_at <= '{}'", created_at_end).to_string()
);
}
}
}

println!("### QUERY: SELECT * FROM metrics {};", filter_clause);

let query_string = format!("SELECT * FROM metrics {} ORDER BY id LIMIT 10", filter_clause);
let results = sql_query(query_string)
.load(&db_conn)
.expect("Error loading metrics");

Json(results)
}

fn main() {
println!("### Enter the Metrix ###");
let db_conn = establish_connection();
Expand All @@ -51,6 +121,6 @@ fn main() {

rocket::ignite()
.mount("/ping", routes![ping])
.mount("/metrics", routes![create_metric_route])
.mount("/metrics", routes![create_metric_route, query_metric_route])
.launch();
}
5 changes: 2 additions & 3 deletions metrix/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use super::schema::metrics;
use serde_json;
use chrono::naive::NaiveDateTime;

#[derive(Serialize, Deserialize, Queryable)]
// #[table_name="metrics"] -- idk why it throws compile error
// "error: cannot find attribute `table_name` in this scope" ...
#[derive(Serialize, Deserialize, Queryable, QueryableByName)]
#[table_name="metrics"]
pub struct Metric {
pub id: i32,
pub metric_name: String,
Expand Down

0 comments on commit 1255c02

Please sign in to comment.