Skip to content

Commit e474f12

Browse files
committed
Allow loading schema from SDL definition file as well as JSON
If passing a path to a file with a name that ends in ".graphql" or ".graphqls" (matching the filenames used in [graphql-ruby](https://github.com/rmosolgo/graphql-ruby/blob/master/lib/graphql/schema.rb#L116)), attempt to load the schema from that file assuming it's a schema definition rather than a JSON schema.
1 parent a81766d commit e474f12

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/graphql/client.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,12 @@ def self.load_schema(schema)
5454
when String
5555
if schema.end_with?(".json") && File.exist?(schema)
5656
load_schema(File.read(schema))
57+
elsif (schema.end_with?(".graphql", ".graphqls")) && File.exist?(schema)
58+
GraphQL::Schema.from_definition(schema)
5759
elsif schema =~ /\A\s*{/
5860
load_schema(JSON.parse(schema, freeze: true))
61+
elsif schema.start_with?("schema")
62+
GraphQL::Schema.from_definition(schema)
5963
end
6064
else
6165
if schema.respond_to?(:execute)

test/test_client_schema.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,22 @@ def test_load_schema_from_json_string
4242
assert_equal "AwesomeQuery", schema.query.graphql_name
4343
end
4444

45+
def test_load_schema_from_definition_string
46+
definition = Schema.to_definition
47+
schema = GraphQL::Client.load_schema(definition)
48+
assert_equal "AwesomeQuery", schema.query.graphql_name
49+
end
50+
51+
def test_load_schema_from_definition_file
52+
definition = Schema.to_definition
53+
Tempfile.create(["schema", ".graphql"]) do |file|
54+
file.write(definition)
55+
file.close
56+
schema = GraphQL::Client.load_schema(file.path)
57+
assert_equal "AwesomeQuery", schema.query.graphql_name
58+
end
59+
end
60+
4561
def test_load_schema_ignores_missing_path
4662
refute GraphQL::Client.load_schema("#{__dir__}/missing-schema.json")
4763
end

0 commit comments

Comments
 (0)