Class: Graphql::Generators::InstallGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/graphql/install_generator.rb

Overview

Add GraphQL to a Rails app with rails g graphql:install.

Setup a folder structure for GraphQL:

- app/
  - graphql/
    - resolvers/
    - types/
      - query_type.rb
    - loaders/
    - mutations/
    - {app_name}_schema.rb

(Add .gitkeeps by default, support --skip-keeps)

Add a controller for serving GraphQL queries:

app/controllers/graphql_controller.rb

Add a route for that controller:

# config/routes.rb
post "/graphql", to: "graphql#execute"

Accept a --relay option which adds The root node(id: ID!) field.

Accept a --batch option which adds GraphQL::Batch setup.

Use --no-graphiql to skip graphiql-rails installation.

Constant Summary collapse

GRAPHIQL_ROUTE =
"if Rails.env.development?\n    mount GraphiQL::Rails::Engine, at: \"/graphiql\", graphql_path: \"/graphql\"\n  end\n"

Instance Method Summary collapse

Instance Method Details

#create_folder_structureObject



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/generators/graphql/install_generator.rb', line 83

def create_folder_structure
  create_dir("app/graphql/mutations")
  create_dir("app/graphql/types")
  template("query_type.erb", "app/graphql/types/query_type.rb")
  template("schema.erb", "app/graphql/#{schema_name.underscore}.rb")
  template("graphql_controller.erb", "app/controllers/graphql_controller.rb")
  route('post "/graphql", to: "graphql#execute"')

  if options[:batch]
    gem("graphql-batch")
    create_dir("app/graphql/loaders")
  end

  if options.api?
    say("Skipped graphiql, as this rails project is API only")
    say("  You may wish to use GraphiQL.app for development: https://github.com/skevy/graphiql-app")
  elsif !options[:skip_graphiql]
    gem("graphiql-rails", group: :development)

    # This is a little cheat just to get cleaner shell output:
    log :route, 'graphiql-rails'
    shell.mute do
      route(GRAPHIQL_ROUTE)
    end
  end

  if gemfile_modified?
    say "Gemfile has been modified, make sure you `bundle install`"
  end
end