Created
July 7, 2016 20:33
-
-
Save rmosolgo/2b9355222f9a1a53d1fd95ce1cc6b86b to your computer and use it in GitHub Desktop.
An idea for tracking fields in GraphQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# An untested idea to add performance tracking to graphql queries | |
# | |
# TODO: what's the best way of tracking time in the app? `Time.now.to_f`? | |
# | |
# When you define your schema, you could add this middleware: | |
# | |
# ``` | |
# MySchema.middleware << PerformanceTrackingMiddleware.new | |
# ``` | |
# | |
# More about middlewares for the GraphQL gem: https://github.com/rmosolgo/graphql-ruby/blob/master/guides/defining_your_schema.md#middleware | |
# | |
class PerformanceTrackingMiddleware | |
def call(parent_type, parent_object, field_definition, field_args, query_context, next_middleware) | |
field_name = "#{parent_type.name}.#{field_definition.name}" | |
field_args_string = field_args.to_h.to_json | |
# Get the time _before_ resolving | |
before_time = Time.now | |
# Resolve the field as normal: | |
resolved_object = next_middleware.call | |
# Get the time _after_ resolving | |
after_time = Time.now | |
# Push your info to whatever tracking service | |
TrackingService.track_event( | |
event_name: field_name, | |
event_metadata: field_args_string, | |
duration: after_time - before_time | |
) | |
# Return the resolved object: | |
resolved_object | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment