Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add metric query endpoint #8

Merged
merged 8 commits into from
Nov 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for limit 10?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to test pagination, we can change it, nbd.

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