├── Gemfile ├── public └── graphiql-rails │ ├── javascripts │ └── stylesheets ├── config └── routes.rb ├── .codeclimate.yml ├── lib └── graphiql │ ├── rails │ ├── version.rb │ ├── engine.rb │ └── config.rb │ └── rails.rb ├── .gitignore ├── test ├── dummy │ ├── config │ │ ├── routes.rb │ │ ├── boot.rb │ │ ├── environment.rb │ │ ├── application.rb │ │ ├── environments │ │ │ ├── development.rb │ │ │ ├── test.rb │ │ │ └── production.rb │ │ └── secrets.yml │ └── config.ru ├── graphiql │ ├── rails │ │ ├── engine_test.rb │ │ └── config_test.rb │ └── rails_test.rb ├── test_helper.rb └── controllers │ └── editors_controller_test.rb ├── .travis.yml ├── app ├── assets │ └── stylesheets │ │ └── graphiql │ │ └── rails │ │ └── application.css ├── controllers │ └── graphiql │ │ └── rails │ │ └── editors_controller.rb └── views │ └── graphiql │ └── rails │ └── editors │ └── show.html.erb ├── Rakefile ├── package.json ├── webpack.config.js ├── .github └── workflows │ └── test.yml ├── LICENSE ├── graphiql-rails.gemspec ├── readme.md ├── javascript └── application.js └── changelog.md /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | gemspec 3 | -------------------------------------------------------------------------------- /public/graphiql-rails/javascripts: -------------------------------------------------------------------------------- 1 | ../../app/assets/javascripts/graphiql/rails -------------------------------------------------------------------------------- /public/graphiql-rails/stylesheets: -------------------------------------------------------------------------------- 1 | ../../app/assets/stylesheets/graphiql/rails -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | GraphiQL::Rails::Engine.routes.draw do 2 | get "/", to: "editors#show" 3 | end 4 | -------------------------------------------------------------------------------- /.codeclimate.yml: -------------------------------------------------------------------------------- 1 | engines: 2 | ratings: 3 | paths: 4 | - "**.rb" 5 | exclude_paths: 6 | - spec/**/* 7 | -------------------------------------------------------------------------------- /lib/graphiql/rails/version.rb: -------------------------------------------------------------------------------- 1 | module GraphiQL 2 | module Rails 3 | VERSION = "1.10.5" 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /test/dummy/log 2 | /test/dummy/tmp 3 | /pkg 4 | /graphiql_update 5 | .ruby-version 6 | Gemfile.lock 7 | node_modules/ 8 | yarn.lock 9 | -------------------------------------------------------------------------------- /test/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/my/graphql/endpoint" 3 | end 4 | -------------------------------------------------------------------------------- /test/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | -------------------------------------------------------------------------------- /test/dummy/config.ru: -------------------------------------------------------------------------------- 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 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | language: ruby 3 | sudo: false 4 | cache: bundler 5 | env: CODECLIMATE_REPO_TOKEN=06fc877a3d350f9e7c2945da8f3ab04ec2d6861001bc89acf2f020de4d520577 6 | rvm: 7 | - "2.2.2" 8 | -------------------------------------------------------------------------------- /test/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /test/graphiql/rails/engine_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class EngineTest < ActiveSupport::TestCase 4 | test "it is defined" do 5 | assert GraphiQL::Rails::Engine 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /app/assets/stylesheets/graphiql/rails/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | = require ./graphiql-3.8.3 3 | */ 4 | 5 | html, body, #graphiql-container { 6 | height: 100%; 7 | margin: 0; 8 | overflow: hidden; 9 | width: 100%; 10 | } 11 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'bundler/setup' 2 | Bundler::GemHelper.install_tasks 3 | 4 | require 'rake/testtask' 5 | 6 | Rake::TestTask.new do |t| 7 | t.libs << "test" << "lib" 8 | t.pattern = "test/**/*_test.rb" 9 | end 10 | 11 | task(default: :test) 12 | -------------------------------------------------------------------------------- /test/graphiql/rails_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | module GraphiQL 4 | class RailsTest < ActiveSupport::TestCase 5 | test "configs can be set" do 6 | refute GraphiQL::Rails.config.query_params 7 | GraphiQL::Rails.config.query_params = true 8 | assert GraphiQL::Rails.config.query_params 9 | GraphiQL::Rails.config.query_params = false 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | require "codeclimate-test-reporter" 2 | CodeClimate::TestReporter.start 3 | 4 | ENV["RAILS_ENV"] = "test" 5 | require File.expand_path("../dummy/config/environment.rb", __FILE__) 6 | require "rails/test_help" 7 | require "rails/generators" 8 | require 'minitest/mock' 9 | 10 | Rails.backtrace_cleaner.remove_silencers! 11 | 12 | Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } 13 | -------------------------------------------------------------------------------- /app/controllers/graphiql/rails/editors_controller.rb: -------------------------------------------------------------------------------- 1 | module GraphiQL 2 | module Rails 3 | class EditorsController < ActionController::Base 4 | def show 5 | end 6 | 7 | helper_method :graphql_endpoint_path 8 | def graphql_endpoint_path 9 | params[:graphql_path] || raise(%|You must include `graphql_path: "/my/endpoint"` when mounting GraphiQL::Rails::Engine|) 10 | end 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require "action_controller/railtie" 4 | require "action_mailer/railtie" 5 | require "rails/test_unit/railtie" 6 | 7 | # Require the gems listed in Gemfile, including any gems 8 | # you've limited to :test, :development, or :production. 9 | Bundler.require(*Rails.groups) 10 | 11 | module Dummy 12 | class Application < Rails::Application 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "graphiql-rails-build-pipeline", 3 | "devDependencies": { 4 | "@graphiql/toolkit": "0.11.1", 5 | "graphiql": "3.8.3", 6 | "graphql": "16.10.0", 7 | "react": "18.0.0", 8 | "react-dom": "18.0.0", 9 | "webpack": "5.98.0", 10 | "webpack-cli": "^6.0.1" 11 | }, 12 | "private": true, 13 | "scripts": { 14 | "build": "webpack && rm app/assets/javascripts/graphiql/rails/application.js.LICENSE.txt" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const webpack = require('webpack'); 3 | 4 | new webpack.DefinePlugin({ 5 | 'process.env.NODE_ENV': '"PRODUCTION"', 6 | }); 7 | 8 | module.exports = { 9 | entry: './javascript/application.js', 10 | mode: "production", 11 | output: { 12 | filename: 'application.js', 13 | path: path.resolve(__dirname, 'app/assets/javascripts/graphiql/rails'), 14 | chunkFormat: false, 15 | }, 16 | devtool: false 17 | }; 18 | -------------------------------------------------------------------------------- /lib/graphiql/rails/engine.rb: -------------------------------------------------------------------------------- 1 | module GraphiQL 2 | module Rails 3 | class Engine < ::Rails::Engine 4 | isolate_namespace GraphiQL::Rails 5 | 6 | if defined?(Sprockets) && Sprockets::VERSION.chr.to_i >= 4 7 | initializer 'graphiql.assets.precompile' do |app| 8 | app.config.assets.precompile += ["graphiql/rails/application.css"] 9 | end 10 | elsif !defined?(Propshaft) 11 | initializer 'graphiql.assets.public' do |app| 12 | app.middleware.use(ActionDispatch::Static, "#{root}/public") 13 | end 14 | end 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: pull_request 3 | 4 | jobs: 5 | test: 6 | strategy: 7 | fail-fast: false 8 | matrix: 9 | include: 10 | - gemfile: Gemfile 11 | ruby: 3.0 12 | - gemfile: Gemfile 13 | ruby: 3.4 14 | runs-on: ubuntu-20.04 15 | steps: 16 | - run: echo BUNDLE_GEMFILE=${{ matrix.gemfile }} > $GITHUB_ENV 17 | - uses: actions/checkout@v2 18 | - uses: ruby/setup-ruby@v1 19 | with: 20 | ruby-version: ${{ matrix.ruby }} 21 | bundler-cache: true 22 | bundler: ${{ matrix.bundler || 'default' }} 23 | - run: bundle exec rake test 24 | -------------------------------------------------------------------------------- /lib/graphiql/rails.rb: -------------------------------------------------------------------------------- 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 27 | -------------------------------------------------------------------------------- /test/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 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 | # Raises error for missing translations 23 | # config.action_view.raise_on_missing_translations = true 24 | end 25 | -------------------------------------------------------------------------------- /test/dummy/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: 78457268f3f9b0c3efa88ac47c71f8277dd1723a5d406ac9e81aa1d179c7881200fdc23ee1d2be84887fb18490c380563d4a009eb887829ec0309d00208a7a7f 15 | 16 | test: 17 | secret_key_base: 79a80a1136851a8ca2823ddb922c3827d8f728bc223a1e713313d919116b5b34ebf28dcd553f3bde35ff27e5c35bcdb93782e61c02d1b493390b4f0aa9767858 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Robert Mosolgo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /graphiql-rails.gemspec: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.push File.expand_path("../lib", __FILE__) 2 | 3 | require "graphiql/rails/version" 4 | require "date" 5 | 6 | Gem::Specification.new do |s| 7 | s.name = 'graphiql-rails' 8 | s.version = GraphiQL::Rails::VERSION 9 | s.date = Date.today.to_s 10 | s.summary = "A mountable GraphiQL endpoint for Rails" 11 | s.description = "Use the GraphiQL IDE for GraphQL with Ruby on Rails. This gem includes an engine, a controller and a view for integrating GraphiQL with your app." 12 | s.homepage = 'http://github.com/rmosolgo/graphiql-rails' 13 | s.authors = ["Robert Mosolgo"] 14 | s.email = ['rdmosolgo@gmail.com'] 15 | s.license = "MIT" 16 | s.required_ruby_version = '>= 2.1.0' # bc optional keyword args 17 | 18 | s.files = Dir["{app,config,lib,public}/**/*"] 19 | 20 | s.add_runtime_dependency "railties" 21 | 22 | s.add_development_dependency "rails" 23 | s.add_development_dependency "sqlite3" 24 | s.add_development_dependency "codeclimate-test-reporter", '~>0.4' 25 | s.add_development_dependency "minitest", "~> 5" 26 | s.add_development_dependency "minitest-focus", "~> 1.1" 27 | s.add_development_dependency "minitest-reporters", "~>1.0" 28 | s.add_development_dependency "rake" 29 | s.add_development_dependency "puma" 30 | end 31 | -------------------------------------------------------------------------------- /test/graphiql/rails/config_test.rb: -------------------------------------------------------------------------------- 1 | require "test_helper" 2 | 3 | class ConfigTest < ActiveSupport::TestCase 4 | class MockViewContext 5 | attr_accessor :customer_header_value 6 | 7 | def form_authenticity_token 8 | "abc-123" 9 | end 10 | end 11 | 12 | setup do 13 | @config = GraphiQL::Rails::Config.new 14 | @config.headers["X-Custom-Header"] = ->(view_context) { view_context.customer_header_value } 15 | @view_context = MockViewContext.new 16 | end 17 | 18 | test "it adds CSRF header if requested" do 19 | assert_equal "abc-123", @config.resolve_headers(@view_context)["X-CSRF-Token"] 20 | @config.csrf = false 21 | assert_nil @config.resolve_headers(@view_context)["X-CSRF-Token"] 22 | end 23 | 24 | test "it adds JSON header by default" do 25 | assert_equal "application/json", @config.resolve_headers(@view_context)["Content-Type"] 26 | end 27 | 28 | test "when the customer header value is nil it is not added" do 29 | @view_context.customer_header_value = nil 30 | assert_equal @config.resolve_headers(@view_context).has_key?("X-Custom-Header"), false 31 | end 32 | 33 | test "when the customer header value is not nil it is added" do 34 | @view_context.customer_header_value = "some-value" 35 | assert_equal "some-value", @config.resolve_headers(@view_context)["X-Custom-Header"] 36 | end 37 | end 38 | -------------------------------------------------------------------------------- /app/views/graphiql/rails/editors/show.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | <%= GraphiQL::Rails.config.title || 'GraphiQL' %> 5 | <% if defined?(Propshaft) %> 6 | <%= stylesheet_link_tag("graphiql/rails/graphiql-3.8.3") %> 7 | <%= stylesheet_link_tag("graphiql/rails/application") %> 8 | <%= javascript_include_tag("graphiql/rails/application", nonce: true ) %> 9 | <% elsif defined?(Sprockets) %> 10 | <%= stylesheet_link_tag("graphiql/rails/application") %> 11 | <%= javascript_include_tag("graphiql/rails/application", nonce: true ) %> 12 | <% else %> 13 | <%= stylesheet_link_tag("/graphiql-rails/stylesheets/graphiql-3.8.3.css") %> 14 | <%= stylesheet_link_tag("/graphiql-rails/stylesheets/application.css?v=#{GraphiQL::Rails::VERSION}") %> 15 | <%= javascript_include_tag("/graphiql-rails/javascripts/application.js?v=#{GraphiQL::Rails::VERSION}", nonce: true) %> 16 | <% end %> 17 | 18 | 19 | <%= content_tag :div, 'Loading...', id: 'graphiql-container', data: { 20 | graphql_endpoint_path: graphql_endpoint_path, 21 | initial_query: GraphiQL::Rails.config.initial_query, 22 | logo: GraphiQL::Rails.config.logo, 23 | headers: GraphiQL::Rails.config.resolve_headers(self), 24 | query_params: GraphiQL::Rails.config.query_params, 25 | header_editor_enabled: GraphiQL::Rails.config.header_editor_enabled, 26 | input_value_deprecation: GraphiQL::Rails.config.input_value_deprecation, 27 | should_persist_headers: GraphiQL::Rails.config.should_persist_headers 28 | } %> 29 | 30 | 31 | -------------------------------------------------------------------------------- /lib/graphiql/rails/config.rb: -------------------------------------------------------------------------------- 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 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, :header_editor_enabled, :input_value_deprecation, :should_persist_headers 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, input_value_deprecation: false) 21 | @query_params = query_params 22 | @headers = headers.dup 23 | @initial_query = initial_query 24 | @title = title 25 | @logo = logo 26 | @csrf = csrf 27 | @input_value_deprecation = input_value_deprecation 28 | end 29 | 30 | # Call defined procs, add CSRF token if specified 31 | def resolve_headers(view_context) 32 | all_headers = DEFAULT_HEADERS.merge(headers) 33 | 34 | if csrf 35 | all_headers = all_headers.merge(CSRF_TOKEN_HEADER) 36 | end 37 | 38 | all_headers.each_with_object({}) do |(key, value), memo| 39 | header_value = value.call(view_context) 40 | memo[key] = header_value if !header_value.nil? 41 | end 42 | end 43 | end 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /test/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 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 43 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # GraphiQL-Rails [![Gem Version](https://badge.fury.io/rb/graphiql-rails.svg)](https://badge.fury.io/rb/graphiql-rails) [![Tests](https://github.com/rmosolgo/graphiql-rails/actions/workflows/test.yml/badge.svg)](https://github.com/rmosolgo/graphiql-rails/actions/workflows/test.yml) 2 | 3 | Mount the [GraphiQL IDE](https://github.com/graphql/graphiql) in Ruby on Rails. 4 | 5 | ![image](https://cloud.githubusercontent.com/assets/2231765/12101544/4779ed54-b303-11e5-918e-9f3d3e283170.png) 6 | 7 | ## Installation 8 | 9 | Add to your Gemfile: 10 | 11 | ```ruby 12 | bundle add graphiql-rails 13 | ``` 14 | 15 | ## Usage 16 | 17 | ### Mount the Engine 18 | 19 | Add the engine to `routes.rb`: 20 | 21 | ```ruby 22 | # config/routes.rb 23 | Rails.application.routes.draw do 24 | # ... 25 | if Rails.env.development? 26 | mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/your/endpoint" 27 | end 28 | end 29 | ``` 30 | 31 | - `at:` is the path where GraphiQL will be served. You can access GraphiQL by visiting that path in your app. 32 | - `graphql_path:` is the path to the GraphQL endpoint. GraphiQL will send queries to this path. 33 | 34 | ### Configuration 35 | 36 | You can override `GraphiQL::Rails.config` values in an initializer (eg, `config/initializers/graphiql.rb`). The configs are: 37 | 38 | - `query_params` (boolean, default `false`): if `true`, the GraphQL query string will be persisted the page's query params 39 | - `initial_query` (string, default `nil`): if provided, it will be rendered in the query pane for a visitor's first visit 40 | - `title` (string, default `nil`): if provided, it will be rendered in the page tag 41 | - `logo` (string, default `nil`): if provided, it will be the text logo 42 | - `csrf` (boolean, default `true`): include `X-CSRF-Token` in GraphiQL's HTTP requests 43 | - `header_editor_enabled` (boolean, default `false`): if provided, the header editor will be rendered 44 | - `headers` (hash, `String => Proc`): procs to fetch header values for GraphiQL's HTTP requests, in the form `(view_context) -> { ... }`. For example: 45 | 46 | ```ruby 47 | GraphiQL::Rails.config.headers['Authorization'] = -> (context) { "bearer #{context.cookies['_graphql_token']}" } 48 | ``` 49 | 50 | - `input_value_deprecation` (boolean, default `false`): if provided, the deprecated arguments will be rendered 51 | - `should_persist_headers` (boolean, default `nil`): if `true`, the headers in the editor will be persisted. If `false`, the toggle for 'Persist headers' will not be shown in the settings 52 | 53 | ### Development 54 | 55 | - Tests: `rake test` 56 | - Build JS: `yarn run build` 57 | -------------------------------------------------------------------------------- /test/controllers/editors_controller_test.rb: -------------------------------------------------------------------------------- 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 | Object.const_set(:Sprockets, :something) 9 | end 10 | 11 | teardown do 12 | GraphiQL::Rails.config.query_params = false 13 | GraphiQL::Rails.config.initial_query = nil 14 | GraphiQL::Rails.config.title = nil 15 | GraphiQL::Rails.config.logo = nil 16 | GraphiQL::Rails.config.headers = {} 17 | Object.send(:remove_const, :Sprockets) 18 | end 19 | 20 | def graphql_params 21 | { params: { graphql_path: '/my/endpoint' } } 22 | end 23 | 24 | test 'renders GraphiQL' do 25 | get :show, **graphql_params 26 | assert_response(:success) 27 | assert_includes(@response.body, 'my/endpoint', 'it uses the provided path') 28 | # If sprockets was actually loaded, it would apply a digest to this: 29 | assert_match(/application\.js/, @response.body, 'it includes assets') 30 | end 31 | 32 | test 'it uses initial_query config' do 33 | GraphiQL::Rails.config.initial_query = '{ customQuery(id: "123") }' 34 | get :show, **graphql_params 35 | assert_includes(@response.body, '"{ customQuery(id: "123") }"') 36 | 37 | GraphiQL::Rails.config.initial_query = nil 38 | get :show, **graphql_params 39 | refute_includes(@response.body, '"{ customQuery(id: "123") }"') 40 | end 41 | 42 | test 'it uses title config' do 43 | GraphiQL::Rails.config.title = 'Custom Title' 44 | get :show, **graphql_params 45 | assert_includes(@response.body, '<title>Custom Title') 46 | 47 | GraphiQL::Rails.config.title = nil 48 | get :show, **graphql_params 49 | assert_includes(@response.body, 'GraphiQL') 50 | end 51 | 52 | test 'it uses logo config' do 53 | GraphiQL::Rails.config.logo = 'Custom Logo' 54 | get :show, **graphql_params 55 | assert_includes(@response.body, %(data-logo="Custom Logo")) 56 | 57 | GraphiQL::Rails.config.logo = nil 58 | get :show, **graphql_params 59 | refute_includes(@response.body, %(data-logo="Custom Logo")) 60 | end 61 | 62 | test 'it uses query_params config' do 63 | get :show, **graphql_params 64 | assert_includes(@response.body, %(data-query-params="false")) 65 | 66 | GraphiQL::Rails.config.query_params = true 67 | get :show, **graphql_params 68 | assert_includes(@response.body, %(data-query-params="true")) 69 | end 70 | 71 | test 'it renders headers' do 72 | GraphiQL::Rails.config.headers['Nonsense-Header'] = ->(_view_ctx) { 'Value' } 73 | get :show, **graphql_params 74 | assert_includes(@response.body, %("Nonsense-Header":"Value")) 75 | assert_includes(@response.body, %("X-CSRF-Token":")) 76 | end 77 | end 78 | end 79 | end 80 | -------------------------------------------------------------------------------- /javascript/application.js: -------------------------------------------------------------------------------- 1 | 2 | import { GraphiQL } from "graphiql"; 3 | import React from "react"; 4 | import { createRoot } from "react-dom/client"; 5 | import { createGraphiQLFetcher } from '@graphiql/toolkit'; 6 | 7 | document.addEventListener("DOMContentLoaded", function (_) { 8 | const graphiqlContainer = document.getElementById("graphiql-container"); 9 | const graphQLEndpoint = graphiqlContainer.dataset.graphqlEndpointPath; 10 | const providedHeaders = JSON.parse(graphiqlContainer.dataset.headers); 11 | 12 | const customFetch = function(url, options) { 13 | options.credentials = "include" 14 | return fetch(url, options) 15 | } 16 | 17 | const fetcher = createGraphiQLFetcher({ 18 | url: graphQLEndpoint, 19 | headers: providedHeaders, 20 | fetch: customFetch, 21 | enableIncrementalDelivery: true, 22 | }) 23 | 24 | // Render into the body. 25 | const initialQuery = graphiqlContainer.dataset.initialQuery; 26 | const shouldPersistHeaders = graphiqlContainer.dataset.shouldPersistHeaders; 27 | let elementProps = { 28 | fetcher: fetcher, 29 | defaultQuery: initialQuery ? initialQuery : undefined, 30 | headerEditorEnabled: graphiqlContainer.dataset.headerEditorEnabled === 'true', 31 | inputValueDeprecation: graphiqlContainer.dataset.inputValueDeprecation === 'true', 32 | shouldPersistHeaders: shouldPersistHeaders ? shouldPersistHeaders === 'true' : undefined 33 | }; 34 | 35 | if (graphiqlContainer.dataset.queryParams === 'true') { 36 | let parameters = {}; 37 | 38 | // Parse the search string to get url parameters 39 | window.location.search.substring(1).split('&').forEach(function (entry) { 40 | let eq = entry.indexOf('='); 41 | if (eq >= 0) { 42 | parameters[decodeURIComponent(entry.slice(0, eq))] = decodeURIComponent(entry.slice(eq + 1)); 43 | } 44 | }); 45 | 46 | // If variables was provided, try to format it 47 | if (parameters.variables) { 48 | try { 49 | parameters.variables = JSON.stringify(JSON.parse(parameters.variables), null, 2); 50 | } catch { 51 | // Do nothing, we want to display the invalid JSON as a string, rather than present an error 52 | } 53 | } 54 | 55 | // When the query and variables string is edited, update the URL bar so that it can be easily shared 56 | function updateURL() { 57 | const newSearch = '?' + Object.keys(parameters).map(function (key) { 58 | return encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]); 59 | }).join('&'); 60 | history.replaceState(null, null, newSearch); 61 | } 62 | 63 | function onEditQuery(newQuery) { 64 | parameters.query = newQuery; 65 | updateURL(); 66 | } 67 | 68 | function onEditVariables(newVariables) { 69 | parameters.variables = newVariables; 70 | updateURL(); 71 | } 72 | 73 | Object.assign(elementProps, { 74 | query: parameters.query, 75 | variables: parameters.variables, 76 | onEditQuery: onEditQuery, 77 | onEditVariables: onEditVariables 78 | }) 79 | } 80 | 81 | const root = createRoot(document.getElementById("graphiql-container")) 82 | root.render( 83 | React.createElement(GraphiQL, elementProps, 84 | React.createElement(GraphiQL.Logo, {}, graphiqlContainer.dataset.logo) 85 | ) 86 | ); 87 | }); 88 | -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | # graphiql-rails 2 | 3 | ## 1.10.5 4 | 5 | - Fix: Add `ActionDispatch::Static` middleware even when it's not already present in the app #126 6 | 7 | ## 1.10.4 8 | 9 | - Fix: Add `public/` to published gem 10 | 11 | ## 1.10.3 12 | 13 | - Javascript: Use `createGraphiQLFetcher` and `enableIncrementalDelivery: true` #125 14 | 15 | ## 1.10.2 16 | 17 | - Add symlinked assets for serving without Propshaft or Sprockets #123 18 | - Add `should_persist_headers` config #122 19 | 20 | ## 1.10.1 21 | 22 | - Update `routes.rb` for Rails 8 compatibility #119 23 | 24 | ## 1.10.0 25 | 26 | - Update to React 18.2.0 27 | - Update to GraphiQL 3.1.1 28 | - Use `.min` versions of JS dependencies 29 | - Add support for Propshaft 30 | - Remove `fetch` polyfill 31 | - Don't set headers whose procs evaluate to `nil` 32 | - Add `input_value_deprecation` flag to introspect deprecated arguments 33 | 34 | ## 1.9.0 35 | 36 | ## New Features 37 | 38 | - Update to React 17.0.2 39 | - Update to GraphiQL 2.4.0 40 | 41 | ## 1.8.0 42 | 43 | ## New Features 44 | 45 | - Update to React 16.14.0 46 | - Update to GraphiQL 1.4.2 47 | 48 | ## Bug Fixes 49 | 50 | - Add `nonce: true` to work with CSP 51 | - Add assets to the precompile list 52 | - Update query params when editor is updated 53 | - Remove test files from gem build 54 | 55 | ## 1.7.0 (Jan 21 2019) 56 | 57 | ### New Features 58 | 59 | - Use production React.js builds 60 | - Update React to 16.7.0 61 | 62 | ## 1.6.0 (Jan 21 2019) 63 | 64 | ### New Features 65 | 66 | - Move JS into a `