module SnowmanIO module API class Metrics < Grape::API before(&:authenticate!) namespace :metrics do route_param :id do before do @metric = Metric.find(params[:id]) end delete do Extra::Meteor.model_destroy(@metric) end # Returns data to render chart for metric params do requires :duration, values: ["history", "day", "hour", "5min"] end get "render" do if params[:duration] == "5min" to = Utils.floor_5sec(Time.now) from = to - 5.minutes + 5.seconds delta = 5.seconds data = @metric.data_points.where( at: {"$gte" => from, "$lte" => to + delta} ).to_a.group_by { |v| Utils.floor_5sec(v.at).to_i }.map { |k, v| [k, v.count] }.to_h datapoints = [] at = from while at <= to datapoints.push(at: at, count: data[at.to_i].to_i) at += delta end { datapoints: datapoints } else if params[:duration] == "hour" to = Utils.floor_5min(Time.now) from = to - 1.hour + 5.minutes precision = "5min" delta = 5.minutes elsif params[:duration] == "day" to = Time.now.beginning_of_hour from = to - 1.day + 1.hour precision = "hour" delta = 1.hour elsif params[:duration] == "history" to = Time.now.beginning_of_day from = @metric.aggregations.where(precision: "daily").order_by("at" => "asc").first.try(:at) || to precision = "daily" delta = 1.day end data = @metric.aggregations.where( precision: precision, at: {"$gte" => from, "$lte" => to + delta} ).to_a.index_by { |v| v.at.to_i } datapoints = [] at = from while at <= to point = data[at.to_i] datapoints.push( at: at, min: data[at.to_i].try(:min).to_f, avg: data[at.to_i].try(:avg).to_f, up: data[at.to_i].try(:up).to_f, max: data[at.to_i].try(:max).to_f, sum: data[at.to_i].try(:sum).to_f, count: data[at.to_i].try(:count).to_i ) at += delta end { datapoints: datapoints } end end end end end end end