Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ajsharp committed Nov 27, 2019
0 parents commit 4358496
Show file tree
Hide file tree
Showing 14 changed files with 279 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.gem
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Alex Sharp

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
108 changes: 108 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# graphql-rails-generators

A few generators to make it easy to integrate your Rails models with [graphql-ruby](https://github.com/rmosolgo/graphql-ruby). I created this because I was wasting too many keystrokes copying my model schema by hand to create graphql types.

This project contains three generators that look at your ActiveRecord model schema and generates graphql types for you.

* `gql:model_type Post` - Generate a graphql type for a model
* `gql:input Post` - Generate a graphql input type for a model
* `gql:mutation Update Post` - Generate a graphql mutation class for a model

## Installation

```
gem 'graphql-rails-generators', group: :development
```

## Requirements

This library only supports ActiveRecord, though it would be fairly trivial to add support for other ORMs.

## Usage

### gql:model_type

Generate a model type from a model.

```
$ rails generate gql:model_type MODEL_CLASS
```

Result:

```ruby
# app/graphql/post_type.rb
module Types
class PostType < Types::BaseObject
field :id, Int, null: true
field :title, String, null: true
field :body, String, null: true
field :created_at, GraphQL::Types::ISO8601DateTime, null: true
field :updated_at, GraphQL::Types::ISO8601DateTime, null: true
end
end
```

### gql:input MODEL_CLASS

Generate an input type from a model.

```
rails generate gql:input Post
```

Result:
```ruby
# app/graphql/types/post_input.rb
module Types
module Input
class PostInput < Types::BaseInputObject
argument :title, String, required: false
argument :body, String, required: false
end
end
end
```

### gql:mutation MUTATION_PREFIX MODEL_NAME

Generate a mutation class from a model.

A quick note about the mutation generator...

The mutation generator generates something akin to an "upsert" mutation. It takes two arguments: an optional `id` and an optional `attributes`, which is the input type for the model. If you pass an `id`, it will attempt to find the model by the `id` and update it, otherwise it will initialize a new model and attempt to save it.

```
rails generate gql:mutation Update Post
```

Result:
```ruby
# app/graphql/mutations/update_post.rb
module Mutations
class UpdatePost < Mutations::BaseMutation
field :post, Types::PostType, null: true

argument :attributes, Types::Input::PostInput, required: true
argument :id, Int, required: false

def resolve(attributes:, id: nil)
model = find_or_build_model(id)
model.attributes = attributes.to_h
if model.save
{post: model}
else
{errors: model.errors.full_messages}
end
end

def find_or_build_model(id)
if id
Post.find(id)
else
Post.new
end
end
end
end
```
8 changes: 8 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
gemspec = eval(File.read("graphql-rails-generators.gemspec"))

task :build => "#{gemspec.full_name}.gem"

file "#{gemspec.full_name}.gem" => gemspec.files + ["graphql-rails-generators.gemspec"] do
system "gem build graphql-rails-generators.gemspec"
system "git tag v#{GraphqlRailsGenerators::VERSION}"
end
15 changes: 15 additions & 0 deletions graphql-rails-generators.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
require File.expand_path("../lib/graphql-rails-generators/version", __FILE__)
Gem::Specification.new do |s|
s.name = 'graphql-rails-generators'
s.version = GraphqlRailsGenerators::VERSION
s.platform = Gem::Platform::RUBY
s.date = '2019-11-26'
s.summary = "Hola!"
s.description = "A simple hello world gem"
s.authors = ["Alex Sharp"]
s.email = '[email protected]'
s.files = Dir["{lib}/**/*.rb", "LICENSE", "*.md"]
s.require_path = 'lib'
s.homepage = 'https://github.com/ajsharp/graphql-rails-generators'
s.license = 'MIT'
end
5 changes: 5 additions & 0 deletions lib/generators/gql/USAGE
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Description:
Generate GraphQL types, mutations, and input types from your rails models.

Example:
rails generate gql:model_type model_type
32 changes: 32 additions & 0 deletions lib/generators/gql/gql_generator_base.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
require 'rails/generators/base'
# require 'active_support/extend'
module Gql
module GqlGeneratorBase
extend ActiveSupport::Concern

included do
protected
def type_map
{
integer: 'Int',
string: 'String',
boolean: 'Boolean',
decimal: 'Float',
datetime: 'GraphQL::Types::ISO8601DateTime',
date: 'GraphQL::Types::ISO8601Date',
hstore: 'GraphQL::Types::JSON'
}
end

def map_model_types(model_name)
klass = model_name.constantize
associations = klass.reflect_on_all_associations(:belongs_to)
bt_columns = associations.map(&:foreign_key)

klass.columns
.reject { |col| bt_columns.include?(col.name) }
.map { |col| {name: col.name, gql_type: type_map.fetch(col.type)} }
end
end
end
end
17 changes: 17 additions & 0 deletions lib/generators/gql/input_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
require_relative 'gql_generator_base'
module Gql
class InputGenerator < Rails::Generators::Base
include GqlGeneratorBase
source_root File.expand_path('../templates', __FILE__)
argument :model_name, type: :string

def generate_input_type
file_name = model_name

ignore = ['id', 'created_at', 'updated_at']
@fields = map_model_types(model_name).reject { |field| ignore.include?(field[:name]) }

template('input_type.rb', "app/graphql/types/input/#{file_name.underscore}_input.rb")
end
end
end
14 changes: 14 additions & 0 deletions lib/generators/gql/model_type_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require_relative 'gql_generator_base'
module Gql
class ModelTypeGenerator < Rails::Generators::Base
include GqlGeneratorBase
source_root File.expand_path('../templates', __FILE__)
argument :model_name, type: :string

def type
file_name = "#{model_name.underscore}_type"
@fields = map_model_types(model_name)
template('model_type.rb', "app/graphql/types/#{file_name}.rb")
end
end
end
13 changes: 13 additions & 0 deletions lib/generators/gql/mutation_generator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module Gql
class MutationGenerator < Rails::Generators::Base
argument :mutation_prefix, type: :string
argument :model_name, type: :string
source_root File.expand_path('../templates', __FILE__)

def mutation
file_name = "#{mutation_prefix}#{model_name}"
template('model_mutation.rb', "app/graphql/mutations/#{file_name.underscore}.rb")
end
end

end
9 changes: 9 additions & 0 deletions lib/generators/gql/templates/input_type.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module Types
module Input
class <%= @model_name %>Input < Types::BaseInputObject
<% @fields.each do |field| -%>
argument :<%= field[:name] %>, <%= field[:gql_type] %>, required: false
<% end %>
end
end
end
26 changes: 26 additions & 0 deletions lib/generators/gql/templates/model_mutation.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module Mutations
class <%= @mutation_prefix %><%= @model_name %> < Mutations::BaseMutation
field :<%= @model_name.underscore %>, Types::<%= @model_name %>Type, null: true
argument :attributes, Types::Input::<%= @model_name %>Input, required: true
argument :id, Int, required: false

def resolve(attributes:, id: nil)
model = find_or_build_model(id)
model.attributes = attributes.to_h
if model.save
{<%= @model_name.underscore %>: model}
else
{errors: model.errors.full_messages}
end
end

def find_or_build_model(id)
if id
<%= @model_name %>.find(id)
else
<%= @model_name %>.new
end
end
end
end
7 changes: 7 additions & 0 deletions lib/generators/gql/templates/model_type.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module Types
class <%= @model_name %>Type < Types::BaseObject
<% @fields.each do |field| -%>
field :<%= field[:name] %>, <%= field[:gql_type] %>, null: true
<% end %>
end
end
3 changes: 3 additions & 0 deletions lib/graphql-rails-generators/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module GraphqlRailsGenerators
VERSION = '1.0.0'
end

0 comments on commit 4358496

Please sign in to comment.