Skip to content

Commit

Permalink
Make the constraints option available
Browse files Browse the repository at this point in the history
for "GraphQL::Constraint::Directive::Constraintを毎回記述する必要があり少々冗長なため、より簡潔に記述できるAPIを検討中です。"

see https://zenn.dev/mh4gf/articles/graphql-ruby-constraint-directive#fn-cee9-1
  • Loading branch information
hoshinotsuyoshi committed Feb 28, 2024
1 parent c6d5850 commit 7d1d7ba
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,29 @@ type Mutation {
}
```

*tips:* You can use shorthand `constraints:` option if you let your argument class include `GraphQL::Constraint::Directive::ConstraintArgumentKeyword` helper.

```ruby
# optional
# in your argument class
require 'graphql/constraint/directive/constraint_argument_keyword'

module Types
class BaseArgument < GraphQL::Schema::Argument
include GraphQL::Constraint::Directive::ConstraintArgumentKeyword
end
end
```

```ruby
# optional
class CreateBook < BaseMutation
argument :title, String,
required: true,
# shorthand for `directives: { GraphQL::Constraint::Directive::Constraint =>...`
constraints: { min_length: 1, max_length: 200 }
```

## API
### String
#### minLength
Expand Down
23 changes: 23 additions & 0 deletions lib/graphql/constraint/directive/constraint_argument_keyword.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# frozen_string_literal: true

module GraphQL
module Constraint
module Directive
module ConstraintArgumentKeyword
def initialize(name, type, desc = nil, **kwargs)
if kwargs.key?(:constraints)
constraints = kwargs.delete(:constraints)
if constraints
directives = kwargs.delete(:directives) || {}
constraint_directive = GraphQL::Constraint::Directive::Constraint
directives[constraint_directive] = constraints
kwargs[:directives] = directives
end
end

super
end
end
end
end
end

0 comments on commit 7d1d7ba

Please sign in to comment.