Skip to content

Instantly share code, notes, and snippets.

@oriolgual
Created August 8, 2018 10:14
Show Gist options
  • Save oriolgual/a031cf6d76ac6412e9ca4f4c4b99bce8 to your computer and use it in GitHub Desktop.
Save oriolgual/a031cf6d76ac6412e9ca4f4c4b99bce8 to your computer and use it in GitHub Desktop.
# Add this to Core's QueryExtensions
module Decidim
module QueryExtensions
type.field :metrics, [Decidim::Core::MetricType]
argument :names, types[String], "The names of the metrics you want to retrieve"
resolve lambda { | _, args, ctx|
manifests = if args[:names].blank?
metrics_registry.all
else
metrics_registry.all.select do |manifest|
args[:names].include?(manifest.metric_name.to_s)
end
end
manifests.map do |manifest|
Decidim::Core::MetricResolver.new(manifest.metric_name, ctx[:current_organization])
end
}
end
end
# These replace all the metric types.
module Decidim
module Core
MetricType = GraphQL::ObjectType.define do
name "Metric"
field :name, !types.String, "The name of the metric"
field :count, !types.Int, "The last value of the metric"
field :history, [!MetricHistoryType], "The historic values for this metric"
end
end
module Decidim
module Core
MetricHistoryType = GraphQL::ObjectType.define do
name "Metric History"
field :day, !types.Date, "The date when the value was registered"
field :value, !types.Int, "The value of the metric"
end
end
end
# This replaces Decidim::MetricCount and all the metric resolvers
module Decidim
module Core
class MetricResolver
attr_reader :name
def initialize(name, organization)
@name = name
@organization = organization
end
def count
metric_scope.last.cumulative.to_i
end
def history
metric_scope.limit(60).pluck(:day, :quantity).map do |day, quantity|
OpenStruct.new(day: day, value: quantity)
end
end
private
def metric_scope
Decidim::Metric
.where(organization: organization, metric_name: name)
.order(:day, :desc)
end
attr_reader :organization
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment