Generators
If you’re using GraphQL with Ruby on Rails, you can use generators to:
-
setup GraphQL, including GraphiQL, GraphQL::Batch, and Relay
graphql:install
You can add GraphQL to a Rails app with graphql:install:
rails generate graphql:install
This will:
-
Set up a folder structure in
app/graphql/ -
Add schema definition
-
Add base type classes
-
Add a
Querytype definition -
Add a
Mutationtype definition with a base mutation class -
Add a route and controller for executing queries
-
Install
graphiql-rails -
Enable
ActiveRecord::QueryLogsand add GraphQL-related metadata (usingGraphQL::Current)
After installing you can see your new schema by:
-
bundle install -
rails server -
Open
localhost:3000/graphiql
Options
-
--directory=DIRECTORYwill specify the directory where generated files should be saved (default isapp/graphql) -
--schema=MySchemaNamewill be used for naming the schema (default is#{app_name}Schema) -
--skip-graphiqlwill excludegraphiql-railsfrom the setup -
--skip-mutation-root-typewill not create of the mutation root type -
--skip-query-logswill skip the QueryLogs setup -
--relaywill add Relay-specific code to your schema -
--batchwill add GraphQL::Batch to your gemfile and include the setup in your schema -
--playgroundwill includegraphql_playground-railsin the setup (mounted at/playground) -
--apiwill create smaller stack for API only apps
Scaffolding Types
Several generators will add GraphQL types to your project. Run them with -h to see the options:
-
rails g graphql:object -
rails g graphql:input -
rails g graphql:interface -
rails g graphql:union -
rails g graphql:enum -
rails g graphql:scalar
ActiveRecord columns auto-extraction
The graphql:object and graphql:input generators can detect the existence of an ActiveRecord class with the same name, and scaffold all database columns as fields/arguments using appropriate GraphQL types and nullability detection
Options
-
--namespaced-typeswill generate each one of theobject/input/interface/... types under separateTypes::Objects::*/Types::Inputs::*/Types::Interfaces::*/... namespaces and folders
Scaffolding Mutations
You can prepare a Relay Classic mutation with
rails g graphql:mutation #{mutation_name}
Scaffolding ActiveRecord Mutations
You can generate a Relay Classic create, update or delete mutation for a given model with
rails g graphql:mutation_create #{model_class_name} rails g graphql:mutation_update #{model_class_name} rails g graphql:mutation_delete #{model_class_name}
model_class_name accepts both namespace/class_type and Namespace::ClassType formats. This mutation also accepts the --namespaced-types flag, to keep it consistent with the scaffolded Object and Input classes from the type generators
Scaffolding Loaders
You can prepare a GraphQL::Batch loader with
rails g graphql:loader