[Awesome Ruby Gem - Graphiti] Use graphiti_graphql to support GraphQL for Graphiti

graphiti_graphql

GraphQL (and Apollo Federation) support for Graphiti. Serve traditional Rails JSON, JSON:API or GraphQL with the same codebase.

Graphiti makes RESTful Resources a first-class concept. This enables reading and writing a graph of data in a single request, a schema with backwards-compatible guarantee, end-to-end integration test patterns, seamless microservices and much more.

Installation

You can install it as a gem:

1
$ gem install graphiti_graphql

or add it into a Gemfile (Bundler):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Gemfile

gem 'graphiti_graphql'

# graphiti-api/graphiti-rails
# https://github.com/graphiti-api/graphiti-rails
gem 'graphiti-rails'

# For automatic ActiveRecord pagination
gem 'kaminari'

# Test-specific gems
group :development, :test do
gem 'rspec-rails'
gem 'factory_bot_rails'
gem 'faker'
gem 'graphiti_spec_helpers'
end

group :test do
gem 'database_cleaner'
end

Then, run bundle install.

1
$ bundle install

Usages

Routes

Mount the engine:

1
2
3
4
5
6
7
8
# config/routes.rb
Rails.application.routes.draw do
scope path: ApplicationResource.endpoint_namespace, defaults: { format: :jsonapi } do
# ... normal graphiti stuff ...

mount GraphitiGraphQL::Engine, at: "/gql"
end
end

For a default Graphiti app, you can now serve GraphQL by POSTing to /api/v1/gql.

That’s it 🎉!

FAQs

undefined method `to_prepare’ for nil:NilClass (NoMethodError)

1
2
3
$ rails s
/Users/cloudolife/.asdf/installs/ruby/3.0.3/lib/ruby/gems/3.0.0/gems/graphiti_graphql-0.1.14/lib/graphiti_graphql/engine.rb:33:in `block in <class:Engine>': undefined method `to_prepare' for nil:NilClass (NoMethodError)
Did you mean? to_param

Check graphiti_graphql-0.1.14/lib/graphiti_graphql/engine.rb file.

1
2
3
4
5
6
7
8
9
# graphiti_graphql-0.1.14/lib/graphiti_graphql/engine.rb

# In dev mode, resource classes are reloaded, and the new classes
# don't match what's in Graphiti.resources. Make sure everything is
# the most recent available.
# Really this belongs in graphiti-rails but keeping isolated for now
initializer "graphiti_graphql.reload_resources" do |app|
::GraphitiGraphQL::Engine.reloader_class.to_prepare do
resources = []

Local version dependency:

1
2
3
4
5
6
7
8
9
10
11
12
$ ruby -v
ruby 3.0.3p157 (2021-11-24 revision 3fb7d2cadc) [x86_64-darwin21]

$ rails -v
Rails 7.0.0

$ gem list | grep graphiti
graphiti (1.3.5)
graphiti-rails (0.3.0)
graphiti_errors (1.1.2)
graphiti_graphql (0.1.14)
graphiti_spec_helpers (1.1.0)

TODO

References

[1] graphiti-api/graphiti_graphql: GraphQL support for Graphiti - https://github.com/graphiti-api/graphiti_graphql

[2] graphiti_graphql | RubyGems.org | Ruby 社区 Gem 托管 - https://rubygems.org/gems/graphiti_graphql

[3] Stylish Graph APIs | Guides - https://www.graphiti.dev/guides/

[4] graphiti-api/graphiti: Stylish Graph APIs - https://github.com/graphiti-api/graphiti