graphiql-rails-fork 1.4.11

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,14 @@
1
+ module GraphiQL
2
+ module Rails
3
+ class EditorsController < InternalAreaController
4
+ def show
5
+ render layout: false
6
+ end
7
+
8
+ helper_method :graphql_endpoint_path
9
+ def graphql_endpoint_path
10
+ params[:graphql_path] || raise(%|You must include `graphql_path: "/my/endpoint"` when mounting GraphiQL::Rails::Engine|)
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,103 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title><%= GraphiQL::Rails.config.title || 'GraphiQL' %></title>
5
+
6
+ <%= stylesheet_link_tag("graphiql/rails/application") %>
7
+ <%= javascript_include_tag("graphiql/rails/application") %>
8
+ </head>
9
+ <body>
10
+ <div id="graphiql-container">
11
+ Loading...
12
+ </div>
13
+ <script>
14
+ var parameters = {};
15
+
16
+ <% if GraphiQL::Rails.config.query_params %>
17
+ // Parse the search string to get url parameters.
18
+ var search = window.location.search;
19
+ search.substr(1).split('&').forEach(function (entry) {
20
+ var eq = entry.indexOf('=');
21
+ if (eq >= 0) {
22
+ parameters[decodeURIComponent(entry.slice(0, eq))] =
23
+ decodeURIComponent(entry.slice(eq + 1));
24
+ }
25
+ });
26
+ // if variables was provided, try to format it.
27
+ if (parameters.variables) {
28
+ try {
29
+ parameters.variables =
30
+ JSON.stringify(JSON.parse(parameters.variables), null, 2);
31
+ } catch (e) {
32
+ // Do nothing, we want to display the invalid JSON as a string, rather
33
+ // than present an error.
34
+ }
35
+ }
36
+ // When the query and variables string is edited, update the URL bar so
37
+ // that it can be easily shared
38
+ function onEditQuery(newQuery) {
39
+ parameters.query = newQuery;
40
+ updateURL();
41
+ }
42
+ function onEditVariables(newVariables) {
43
+ parameters.variables = newVariables;
44
+ updateURL();
45
+ }
46
+ function updateURL() {
47
+ var newSearch = '?' + Object.keys(parameters).map(function (key) {
48
+ return encodeURIComponent(key) + '=' +
49
+ encodeURIComponent(parameters[key]);
50
+ }).join('&');
51
+ history.replaceState(null, null, newSearch);
52
+ }
53
+ <% end %>
54
+
55
+ // Defines a GraphQL fetcher using the fetch API.
56
+ var graphQLEndpoint = "<%= graphql_endpoint_path %>";
57
+ function graphQLFetcher(graphQLParams) {
58
+ return fetch(graphQLEndpoint, {
59
+ method: 'post',
60
+ headers: <%= raw JSON.pretty_generate(GraphiQL::Rails.config.resolve_headers(self)) %>,
61
+ body: JSON.stringify(graphQLParams),
62
+ credentials: 'include',
63
+ }).then(function(response) {
64
+ try {
65
+ return response.json();
66
+ } catch(error) {
67
+ return {
68
+ "status": response.status,
69
+ "message": "The server responded with invalid JSON, this is probably a server-side error",
70
+ "response": response.text(),
71
+ };
72
+ }
73
+ })
74
+ }
75
+
76
+ <% if GraphiQL::Rails.config.initial_query %>
77
+ var defaultQuery = "<%= GraphiQL::Rails.config.initial_query.gsub("\n", '\n').gsub('"', '\"').html_safe %>";
78
+ <% else %>
79
+ var defaultQuery = undefined
80
+ <% end %>
81
+
82
+ // Render <GraphiQL /> into the body.
83
+ ReactDOM.render(
84
+ React.createElement(GraphiQL,
85
+ {
86
+ fetcher: graphQLFetcher,
87
+ defaultQuery: defaultQuery,
88
+ <% if GraphiQL::Rails.config.query_params %>
89
+ query: parameters.query,
90
+ variables: parameters.variables,
91
+ onEditQuery: onEditQuery,
92
+ onEditVariables: onEditVariables
93
+ <% end %>
94
+ },
95
+ <% if GraphiQL::Rails.config.logo %>
96
+ React.createElement(GraphiQL.Logo, {}, "<%= GraphiQL::Rails.config.logo %>")
97
+ <% end %>
98
+ ),
99
+ document.getElementById("graphiql-container")
100
+ );
101
+ </script>
102
+ </body>
103
+ </html>
@@ -0,0 +1,3 @@
1
+ GraphiQL::Rails::Engine.routes.draw do
2
+ get "/" => "editors#show"
3
+ end
@@ -0,0 +1,26 @@
1
+ require "rails"
2
+
3
+ if ActiveSupport::Inflector.method(:inflections).arity == 0
4
+ # Rails 3 does not take a language in inflections.
5
+ ActiveSupport::Inflector.inflections do |inflect|
6
+ inflect.acronym("GraphiQL")
7
+ end
8
+ else
9
+ ActiveSupport::Inflector.inflections(:en) do |inflect|
10
+ inflect.acronym("GraphiQL")
11
+ end
12
+ end
13
+
14
+ require "graphiql/rails/config"
15
+ require "graphiql/rails/engine"
16
+ require "graphiql/rails/version"
17
+
18
+ module GraphiQL
19
+ module Rails
20
+ class << self
21
+ attr_accessor :config
22
+ end
23
+
24
+ self.config = Config.new
25
+ end
26
+ end
@@ -0,0 +1,43 @@
1
+ module GraphiQL
2
+ module Rails
3
+ class Config
4
+ # @example Adding a header to the request
5
+ # config.headers["My-Header"] = -> (view_context) { "My-Value" }
6
+ #
7
+ # @return [Hash<String => Proc>] Keys are headers to include in GraphQL requests, values are `->(view_context) { ... }` procs to determin values
8
+ attr_accessor :headers
9
+
10
+ attr_accessor :query_params, :initial_query, :csrf, :title, :logo
11
+
12
+ DEFAULT_HEADERS = {
13
+ 'Content-Type' => ->(_) { 'application/json' },
14
+ }
15
+
16
+ CSRF_TOKEN_HEADER = {
17
+ "X-CSRF-Token" => -> (view_context) { view_context.form_authenticity_token }
18
+ }
19
+
20
+ def initialize(query_params: false, initial_query: nil, title: nil, logo: nil, csrf: true, headers: DEFAULT_HEADERS)
21
+ @query_params = query_params
22
+ @headers = headers.dup
23
+ @initial_query = initial_query
24
+ @title = title
25
+ @logo = logo
26
+ @csrf = csrf
27
+ end
28
+
29
+ # Call defined procs, add CSRF token if specified
30
+ def resolve_headers(view_context)
31
+ all_headers = DEFAULT_HEADERS.merge(headers)
32
+
33
+ if csrf
34
+ all_headers = all_headers.merge(CSRF_TOKEN_HEADER)
35
+ end
36
+
37
+ all_headers.each_with_object({}) do |(key, value), memo|
38
+ memo[key] = value.call(view_context)
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,7 @@
1
+ module GraphiQL
2
+ module Rails
3
+ class Engine < ::Rails::Engine
4
+ isolate_namespace GraphiQL::Rails
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,5 @@
1
+ module GraphiQL
2
+ module Rails
3
+ VERSION = "1.4.11"
4
+ end
5
+ end
@@ -0,0 +1,77 @@
1
+ require "test_helper"
2
+
3
+ module GraphiQL
4
+ module Rails
5
+ class EditorsControllerTest < ActionController::TestCase
6
+ setup do
7
+ @routes = GraphiQL::Rails::Engine.routes
8
+ end
9
+
10
+ teardown do
11
+ GraphiQL::Rails.config.query_params = false
12
+ GraphiQL::Rails.config.initial_query = nil
13
+ GraphiQL::Rails.config.title = nil
14
+ GraphiQL::Rails.config.logo = nil
15
+ GraphiQL::Rails.config.headers = {}
16
+ end
17
+
18
+ def graphql_params
19
+ { params: { graphql_path: "/my/endpoint" } }
20
+ end
21
+
22
+ test "renders GraphiQL" do
23
+ get :show, graphql_params
24
+ assert_response(:success)
25
+ assert_includes(@response.body, "React.createElement(GraphiQL", "it renders GraphiQL")
26
+ assert_includes(@response.body, "my/endpoint", "it uses the provided path")
27
+ assert_match(/application-\w+\.js/, @response.body, "it includes assets")
28
+ end
29
+
30
+ test "it uses initial_query config" do
31
+ GraphiQL::Rails.config.initial_query = '{ customQuery(id: "123") }'
32
+ get :show, graphql_params
33
+ assert_includes(@response.body, '"{ customQuery(id: \"123\") }"')
34
+
35
+ GraphiQL::Rails.config.initial_query = nil
36
+ get :show, graphql_params
37
+ refute_includes(@response.body, '"{ customQuery(id: \"123\") }"')
38
+ end
39
+
40
+ test "it uses title config" do
41
+ GraphiQL::Rails.config.title = 'Custom Title'
42
+ get :show, graphql_params
43
+ assert_includes(@response.body, '<title>Custom Title</title>')
44
+
45
+ GraphiQL::Rails.config.title = nil
46
+ get :show, graphql_params
47
+ assert_includes(@response.body, '<title>GraphiQL</title>')
48
+ end
49
+
50
+ test "it uses logo config" do
51
+ GraphiQL::Rails.config.logo = 'Custom Logo'
52
+ get :show, graphql_params
53
+ assert_includes(@response.body, 'React.createElement(GraphiQL.Logo, {}, "Custom Logo")')
54
+
55
+ GraphiQL::Rails.config.logo = nil
56
+ get :show, graphql_params
57
+ refute_includes(@response.body, 'React.createElement(GraphiQL.Logo, {}, "Custom Logo")')
58
+ end
59
+
60
+ test "it uses query_params config" do
61
+ get :show, graphql_params
62
+ refute_includes(@response.body, "onEditQuery")
63
+
64
+ GraphiQL::Rails.config.query_params = true
65
+ get :show, graphql_params
66
+ assert_includes(@response.body, "onEditQuery")
67
+ end
68
+
69
+ test "it renders headers" do
70
+ GraphiQL::Rails.config.headers["Nonsense-Header"] = -> (view_ctx) { "Value" }
71
+ get :show, graphql_params
72
+ assert_includes(@response.body, %|"Nonsense-Header": "Value"|)
73
+ assert_includes(@response.body, %|"X-CSRF-Token": "|)
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,4 @@
1
+ # This file is used by Rack-based servers to start the application.
2
+
3
+ require ::File.expand_path('../config/environment', __FILE__)
4
+ run Rails.application
@@ -0,0 +1,15 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ require "action_controller/railtie"
4
+ require "action_mailer/railtie"
5
+ require "sprockets/railtie"
6
+ require "rails/test_unit/railtie"
7
+
8
+ # Require the gems listed in Gemfile, including any gems
9
+ # you've limited to :test, :development, or :production.
10
+ Bundler.require(*Rails.groups)
11
+
12
+ module Dummy
13
+ class Application < Rails::Application
14
+ end
15
+ end
@@ -0,0 +1,3 @@
1
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
2
+
3
+ require 'bundler/setup' # Set up gems listed in the Gemfile.
@@ -0,0 +1,5 @@
1
+ # Load the Rails application.
2
+ require File.expand_path('../application', __FILE__)
3
+
4
+ # Initialize the Rails application.
5
+ Rails.application.initialize!
@@ -0,0 +1,41 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # In the development environment your application's code is reloaded on
5
+ # every request. This slows down response time but is perfect for development
6
+ # since you don't have to restart the web server when you make code changes.
7
+ config.cache_classes = false
8
+
9
+ # Do not eager load code on boot.
10
+ config.eager_load = false
11
+
12
+ # Show full error reports and disable caching.
13
+ config.consider_all_requests_local = true
14
+ config.action_controller.perform_caching = false
15
+
16
+ # Don't care if the mailer can't send.
17
+ config.action_mailer.raise_delivery_errors = false
18
+
19
+ # Print deprecation notices to the Rails logger.
20
+ config.active_support.deprecation = :log
21
+
22
+ # Raise an error on page load if there are pending migrations.
23
+ config.active_record.migration_error = :page_load
24
+
25
+ # Debug mode disables concatenation and preprocessing of assets.
26
+ # This option may cause significant delays in view rendering with a large
27
+ # number of complex assets.
28
+ config.assets.debug = true
29
+
30
+ # Asset digests allow you to set far-future HTTP expiration dates on all assets,
31
+ # yet still be able to expire them through the digest params.
32
+ config.assets.digest = true
33
+
34
+ # Adds additional error checking when serving assets at runtime.
35
+ # Checks for improperly declared sprockets dependencies.
36
+ # Raises helpful error messages.
37
+ config.assets.raise_runtime_errors = true
38
+
39
+ # Raises error for missing translations
40
+ # config.action_view.raise_on_missing_translations = true
41
+ end
@@ -0,0 +1,79 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # Code is not reloaded between requests.
5
+ config.cache_classes = true
6
+
7
+ # Eager load code on boot. This eager loads most of Rails and
8
+ # your application in memory, allowing both threaded web servers
9
+ # and those relying on copy on write to perform better.
10
+ # Rake tasks automatically ignore this option for performance.
11
+ config.eager_load = true
12
+
13
+ # Full error reports are disabled and caching is turned on.
14
+ config.consider_all_requests_local = false
15
+ config.action_controller.perform_caching = true
16
+
17
+ # Enable Rack::Cache to put a simple HTTP cache in front of your application
18
+ # Add `rack-cache` to your Gemfile before enabling this.
19
+ # For large-scale production use, consider using a caching reverse proxy like
20
+ # NGINX, varnish or squid.
21
+ # config.action_dispatch.rack_cache = true
22
+
23
+ # Disable serving static files from the `/public` folder by default since
24
+ # Apache or NGINX already handles this.
25
+ config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
26
+
27
+ # Compress JavaScripts and CSS.
28
+ config.assets.js_compressor = :uglifier
29
+ # config.assets.css_compressor = :sass
30
+
31
+ # Do not fallback to assets pipeline if a precompiled asset is missed.
32
+ config.assets.compile = false
33
+
34
+ # Asset digests allow you to set far-future HTTP expiration dates on all assets,
35
+ # yet still be able to expire them through the digest params.
36
+ config.assets.digest = true
37
+
38
+ # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
39
+
40
+ # Specifies the header that your server uses for sending files.
41
+ # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
42
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
43
+
44
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
45
+ # config.force_ssl = true
46
+
47
+ # Use the lowest log level to ensure availability of diagnostic information
48
+ # when problems arise.
49
+ config.log_level = :debug
50
+
51
+ # Prepend all log lines with the following tags.
52
+ # config.log_tags = [ :subdomain, :uuid ]
53
+
54
+ # Use a different logger for distributed setups.
55
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
56
+
57
+ # Use a different cache store in production.
58
+ # config.cache_store = :mem_cache_store
59
+
60
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server.
61
+ # config.action_controller.asset_host = 'http://assets.example.com'
62
+
63
+ # Ignore bad email addresses and do not raise email delivery errors.
64
+ # Set this to true and configure the email server for immediate delivery to raise delivery errors.
65
+ # config.action_mailer.raise_delivery_errors = false
66
+
67
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
68
+ # the I18n.default_locale when a translation cannot be found).
69
+ config.i18n.fallbacks = true
70
+
71
+ # Send deprecation notices to registered listeners.
72
+ config.active_support.deprecation = :notify
73
+
74
+ # Use default logging formatter so that PID and timestamp are not suppressed.
75
+ config.log_formatter = ::Logger::Formatter.new
76
+
77
+ # Do not dump schema after migrations.
78
+ config.active_record.dump_schema_after_migration = false
79
+ end
@@ -0,0 +1,42 @@
1
+ Rails.application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb.
3
+
4
+ # The test environment is used exclusively to run your application's
5
+ # test suite. You never need to work with it otherwise. Remember that
6
+ # your test database is "scratch space" for the test suite and is wiped
7
+ # and recreated between test runs. Don't rely on the data there!
8
+ config.cache_classes = true
9
+
10
+ # Do not eager load code on boot. This avoids loading your whole application
11
+ # just for the purpose of running a single test. If you are using a tool that
12
+ # preloads Rails for running tests, you may have to set it to true.
13
+ config.eager_load = false
14
+
15
+ # Configure static file server for tests with Cache-Control for performance.
16
+ config.serve_static_files = true
17
+ config.static_cache_control = 'public, max-age=3600'
18
+
19
+ # Show full error reports and disable caching.
20
+ config.consider_all_requests_local = true
21
+ config.action_controller.perform_caching = false
22
+
23
+ # Raise exceptions instead of rendering exception templates.
24
+ config.action_dispatch.show_exceptions = false
25
+
26
+ # Disable request forgery protection in test environment.
27
+ config.action_controller.allow_forgery_protection = false
28
+
29
+ # Tell Action Mailer not to deliver emails to the real world.
30
+ # The :test delivery method accumulates sent emails in the
31
+ # ActionMailer::Base.deliveries array.
32
+ config.action_mailer.delivery_method = :test
33
+
34
+ # Randomize the order test cases are executed.
35
+ config.active_support.test_order = :random
36
+
37
+ # Print deprecation notices to the stderr.
38
+ config.active_support.deprecation = :stderr
39
+
40
+ # Raises error for missing translations
41
+ # config.action_view.raise_on_missing_translations = true
42
+ end