Skip to content

Commit

Permalink
Merge pull request #756 from datacite/cache_graphql_response
Browse files Browse the repository at this point in the history
Cache graphQL response to improve Commons User Experience
  • Loading branch information
kjgarza authored Sep 16, 2021
2 parents a605818 + ba1e2e4 commit 4afe54d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
9 changes: 3 additions & 6 deletions app/controllers/graphql_controller.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

class GraphqlController < ApplicationController
include Cacheable
before_action :authenticate_user!

def execute
Expand All @@ -11,12 +12,8 @@ def execute
tracing_enabled: ApolloFederation::Tracing.should_add_traces(headers),
current_user: current_user,
}
result =
LupoSchema.execute(
query,
variables: variables, context: context, operation_name: operation_name,
)
render json: ApolloFederation::Tracing.attach_trace_to_result(result)
result = cached_graphql_response(query, variables, context, operation_name)
render json: result
rescue StandardError => e
raise e unless Rails.env.development?

Expand Down
17 changes: 17 additions & 0 deletions app/models/concerns/cacheable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,23 @@ def cached_prefix_response(prefix, _options = {})
end
end

def cached_graphql_response(query, variables, context, operation_name)
hash = Base64.encode64(query.to_json + variables.to_json + context.to_json + operation_name.to_json)
if Rails.application.config.action_controller.perform_caching && !variables[:id].nil?
Rails.cache.fetch("akita_response/#{hash}", expires_in: 24.hours) do
LupoSchema.execute(
query,
variables: variables, context: context, operation_name: operation_name,
).to_json
end
else
LupoSchema.execute(
query,
variables: variables, context: context, operation_name: operation_name,
)
end
end

def cached_resource_type_response(id)
Rails.cache.fetch("resource_type_response/#{id}", expires_in: 1.month) do
resource_type = ResourceType.where(id: id)
Expand Down

0 comments on commit 4afe54d

Please sign in to comment.