Giter VIP home page Giter VIP logo

graphql_java_gen's Introduction

GraphQLJavaGen

Build Status

Generate code for a specific GraphQL schema that provides query builders and response classes.

Installation

The code generator requires ruby version 2.1 or later.

It is recommended to use bundler to install the code generators ruby package.

Add this line to your application's Gemfile:

gem 'graphql_java_gen'

And then execute:

$ bundle

The generated code depends on the com.shopify.graphql.support java package. This can be added to a gradle project by adding the following dependancy to you build.gradle file:

implementation 'com.shopify.graphql.support:support:0.2.1'

Usage

Monolith (single file) schema generation

Create a script that generates the code for a GraphQL API

require 'graphql_java_gen'
require 'graphql_schema'
require 'json'

introspection_result = File.read("graphql_schema.json")
schema = GraphQLSchema.new(JSON.parse(introspection_result))

GraphQLJavaGen.new(schema,
  package_name: "com.example.MyApp",
  nest_under: 'ExampleSchema',
  version: '2020-01',
  custom_scalars: [
    GraphQLJavaGen::Scalar.new(
      type_name: 'Decimal',
      java_type: 'BigDecimal',
      deserialize_expr: ->(expr) { "new BigDecimal(jsonAsString(#{expr}, key))" },
      imports: ['java.math.BigDecimal'],
    ),
  ]
).save("#{Dir.pwd}/../MyApp/src/main/java/com/example/MyApp/ExampleSchema.java")

The generated ExampleSchema.java will include a single class, ExampleSchema, which contains all defined GraphQL schema entities as nested subclasses.

Granular (multiple file) schema generation

You may also generate separate class files for each schema entity using the save_granular command. In this case, you should provide the path to a directory, not a single class.

e.g.

require 'graphql_java_gen'
require 'graphql_schema'
require 'json'

introspection_result = File.read("graphql_schema.json")
schema = GraphQLSchema.new(JSON.parse(introspection_result))

GraphQLJavaGen.new(schema,
  package_name: "com.example.MyApp",
  nest_under: 'ExampleSchema',
  version: '2020-01',
  custom_scalars: [
    GraphQLJavaGen::Scalar.new(
      type_name: 'Decimal',
      java_type: 'BigDecimal',
      deserialize_expr: ->(expr) { "new BigDecimal(jsonAsString(#{expr}, key))" },
      imports: ['java.math.BigDecimal'],
    ),
  ]
).save_granular("#{Dir.pwd}/../MyApp/src/main/java/com/example/MyApp/")

When using the granular option, the com.example.MyApp package will contain many small class files each containing a single GraphQL schema entity.

Generated code

Regardless of whether you use the monolith or granular schema generator, the usage is largely the same. The only difference depends on whether you access the schema entities directly from the provided package or as nested, static classes on the ExampleSchema class.

That generated code depends on the com.shopify.graphql.support package.

The generated code includes a query builder that can be used to create a GraphQL query in a type-safe manner.

String queryString = ExampleSchema.query(query -> query
    .user(user -> user
        .firstName()
        .lastName()
    )
).toString();

The generated code also includes response classes that will deserialize the response and provide methods for accessing the field data with it already coerced to the correct type.

ExampleSchema.QueryResponse response = ExampleSchema.QueryResponse.fromJson(responseJson);
if (!response.getErrors().isEmpty()) {
    for (Error error : response.getErrors()) {
        System.err.println("GraphQL error: " + error.message());
    }
}
if (data != null) {
    ExampleSchema.User user = data.getUser();
    System.out.println("user.firstName() + " " + user.lastName());
}

Lambda Expressions

The java 8 lambda expressions feature is essential for having a nice syntax for the query builder. This feature is also available for Android apps by using the Jack toolchain.

If an older version of java must be used, then retrolambda can be used to backport this feature to java 5-7.

Development

After checking out the repo, run bundle to install ruby dependencies. Then, run rake test to run the tests.

To install this gem onto your local machine, run bundle exec rake install or reference it from a Gemfile using the path option (e.g. gem 'graphql_java_gen', path: '~/src/graphql_java_gen').

Contributing

See our contributing guidelines for more information.

License

The gem is available as open source under the terms of the MIT License.

graphql_java_gen's People

Contributors

benemdon avatar caiopia avatar cocoahero avatar danieljette avatar dylanahsmith avatar eapache avatar henrytao-me avatar jaredh avatar sav007 avatar will-sommers avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graphql_java_gen's Issues

`getNodes` method on AbstractResponse

Currently if your schema has a node type we generate a getNodes helper method on all the classes that implement AbstractResponse. I've run into a case where I would like to have getNodes declared as an abstract method on AbstractResponse.

This isn't quite straightforward since AbstractResponse isn't generated so we can't just remove the method when there is no Node type. We could generate a bunch of empty implementations in that case but it's not ideal.

@dylanahsmith thoughts?

Please, how can I use it?

Can't find the java lib versions on jcenter...

compile 'com.shopify.graphql.support:support:0.2.0'

The gem is outdated!!!!

do.rb:19:in <main>': undefined method save_granular' for #GraphQLJavaGen:0x0000000006eca058 (NoMethodError)

Lost hours trying to follow the instructions to discover the versions are years outdated...

Please make it clear in your docs.

Error code generated for shopify when type has some deprecated fields

For example, since DiscountAutomaticBxgy has a deprecated field id, java code generated for this type in default config will not generated getId() method. But this type implements interface Node which declares getId().
As #26 introduces the feature for deprecated fields, I think there may be some bugs related.

Split generated code into separate files

The output for the code generator can get quite large, which also makes it harder to find things in.

I think it would be nicer to write to separate files for the different GraphQL types.

Generated class doesn't complie

Recently generated class for store front schema started failing during compilation.
With reason:getNodes already defined.

The issue that store front schema has been updated with additional field nodes(ids: [ID!]!): [Node]! under the QueryRoot.

That causes to this conflict:

 public List<Node> getNodes() {
            List<Node> children = new ArrayList<>();

            if (getCustomer() != null) {
                children.addAll(getCustomer().getNodes());
            }

            if (getShop() != null) {
                children.addAll(getShop().getNodes());
            }

            return children;
        }

...

public List<Node> getNodes() {
            return (List<Node>) get("nodes");
        }

I believe that the first function List<Node> getNodes() is just helper method been generated to flatten the fields that implements the same interface Node. But that causes the conflict with the real field that has the same name nodes.

Ref to storefront schema: https://app.shopify.com/services/ping/storefront_graphql_schema

undefined Method "save_granular"

Basically i copied the code from the README

require 'graphql_schema'
require 'json'

introspection_result = File.read("graphql_schema.json")
schema = GraphQLSchema.new(JSON.parse(introspection_result))

GraphQLJavaGen.new(schema,
  package_name: "com.example.MyApp",
  nest_under: 'ExampleSchema',
  custom_scalars: [
    GraphQLJavaGen::Scalar.new(
      type_name: 'Decimal',
      java_type: 'BigDecimal',
      deserialize_expr: ->(expr) { "new BigDecimal(jsonAsString(#{expr}, key))" },
      imports: ['java.math.BigDecimal'],
    ),
  ]
).save_granular("#{Dir.pwd}/../MyApp/src/main/java/com/example/MyApp/")

I changed the filenames and paths, i installed the gems. If i run the file though commandline says

javagen.rb:19:in <main>': undefined method save_granular' for #GraphQLJavaGen:0x0000000003234710 (NoMethodError)

Maybe it is my mistake but i never had anything to do with ruby and have no clue.

Thank you for your help.

Support for Jackson deserialization

Currently the generated code does not support Jackson ser/der when using the generated schema in a Spring Boot project with Jackson.
Jackson expects an empty constructor for the class.

org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type

Any plans to add empty constructor to the generated schema?

Error generating code for schema with unions

Tried to run generation tool against Github Schema got next message:

graphql_schema.rb:203:in `fields': undefined method `map' for nil:NilClass (NoMethodError)
Did you mean?  tap
	from .../templates/APISchema.java.erb:85:in `block in generate'
	from .../templates/APISchema.java.erb:68:in `each'
	from .../templates/APISchema.java.erb:68:in `generate'
	from /opt/rubies/2.3.3/lib/ruby/2.3.0/erb.rb:864:in `eval'
	from /opt/rubies/2.3.3/lib/ruby/2.3.0/erb.rb:864:in `result'
	from .../lib/graphql_java_gen.rb:31:in `generate'
	from.../graphql_java_gen.rb:27:in `save'

The error doesn't tell what type caused the issue.

TopLevelResponse should provide API to be constructed from String

It would be nice com.shopify.graphql.support.TopLevelResponse to have constructor that accepts json string as parameter, and uses com.google.gson.JsonParser internally. So from user perspective no need to know that Gson is used internally and API will be simplified:

graphQlResponse = new TopLevelResponse(response.body().string());

Code generation support not requiring Ruby.

Is there a way to generate code based on a GraphQL API (like GitHub's API) using this project which does not involve Ruby? I think that most Java developers don't want to use Ruby and it is rather cumbersome to use another language's tools to do work with Java.

Errors when field "description" is missing

Using recent versions of graphql-java (7) the ruby generation fails on missing entries for description:

ib/ruby/gems/2.4.0/gems/graphql_schema-0.1.6/lib/graphql_schema.rb:53:in fetch': key not found: "description" (KeyError) from /lib/ruby/gems/2.4.0/gems/graphql_schema-0.1.6/lib/graphql_schema.rb:53:in description'

The description field should perhaps not be mandatory? Earlier versions of the graphql-java library would on missing values for the description field output this:

"types" : [ { "kind" : "OBJECT", "name" : "RootQuery", "description" : null,...

From version 7 onwards, the field is omitted totally if null.

The specs describe the description field as a nullable type.
type GraphQLObjectTypeConfig = { name: string; ... description?: ?string }

http://graphql.org/graphql-js/type/#graphqlobjecttype

The error is actually in https://github.com/Shopify/graphql_schema/blob/master/lib/graphql_schema.rb#L53
def description @hash.fetch('description') end
It should not assume the description field is always present.

not generated nest_under 'ExampleSchema' using save_granular?

I use the below script following README to generate the graphql code, but not found 'ExampleSchema', so how do I use only the XXXQuery?

GraphQLJavaGen.new(schema,
package_name: "com.example.MyApp",
nest_under: 'ExampleSchema',
custom_scalars: [
GraphQLJavaGen::Scalar.new(
type_name: 'Decimal',
java_type: 'BigDecimal',
deserialize_expr: ->(expr) { "new BigDecimal(jsonAsString(#{expr}, key))" },
imports: ['java.math.BigDecimal'],
),
]
).save_granular("#{Dir.pwd}/../MyApp/src/main/java/com/example/MyApp/")

`fetch': key not found: "data" (KeyError)

Hi, I am trying to do this for a shops schema, I downloaded the schema file which is 106k lines. then ran the commands you mentioned in the README. got the error below.

schema file looks like:
shopify-admin.json

{
  "__schema": {
    "queryType": {
      "name": "QueryRoot"
    },
    "mutationType": {
      "name": "Mutation"
    },
    "subscriptionType": null,
    "types": ...,
    "directives": ...,
  }
}

example.ruby

require 'graphql_schema'
require 'graphql_java_gen'
require 'json'

introspection_result = File.read("shopify-admin.json")
schema = GraphQLSchema.new(JSON.parse(introspection_result))

GraphQLJavaGen.new(schema,
  package_name: "com.example.MyApp",
  nest_under: 'ExampleSchema',
  version: '2022-01',
  custom_scalars: [
    GraphQLJavaGen::Scalar.new(
      type_name: 'Decimal',
      java_type: 'BigDecimal',
      deserialize_expr: ->(expr) { "new BigDecimal(jsonAsString(#{expr}, key))" },
      imports: ['java.math.BigDecimal'],
    ),
  ]
).save("#{Dir.pwd}/../MyApp/src/main/java/com/example/MyApp/ExampleSchema.java")

error:

khaled@khaleds-mbp graphql_java_gen-master % ruby example.ruby                                                            
Traceback (most recent call last):
	3: from example.ruby:6:in `<main>'
	2: from example.ruby:6:in `new'
	1: from /Library/Ruby/Gems/2.6.0/gems/graphql_schema-0.1.8/lib/graphql_schema.rb:6:in `initialize'
/Library/Ruby/Gems/2.6.0/gems/graphql_schema-0.1.8/lib/graphql_schema.rb:6:in `fetch': key not found: "data" (KeyError)

versions:
ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.x86_64-darwin19]

{
"dependencies": {
"apollo": "2.33.4",
"graphql": "^14.6.0"
}
}

Accessing an queried field should throw an exception

Because we create response classes for any query, we can't catch this bug at compile time. The next best thing is to detect this and throw an exception so that it is more likely to be caught quickly during testing.

We would like to be able to write some common code that takes values from a response object and sets them on an input object, which will need a way to detect if a field has been set. This could be done by having a has field method.

Support Java library 0.2.0

Hello,

first of all thank you very much for your work and open sourcing this tool, it is of great help!

I tried using generated GraphQL library in my project and noticed that version 0.2.0 (com.shopify.graphql.support:support:0.2.0) of Java support library is not yet published to jCenter (latest version available there is 0.1.1).

I have manually built lib from repo support folder and included in my project, but I thought that you would like to know this and publish support library when you have time.

Once again, thank you very much for your work!

All best,
Sasa

0.2.0 Release?

I am trying to use the newest version of this according to the readme. I would benefit from being able to use the 'save_granular', but when i attempt to install the 0.2.0 gem, it's not able to. Is there a plan to release a 0.2.0 gem version of this anytime soon? or is this a dead repo?

Fetching gem metadata from https://rubygems.org/.. Could not find gem 'graphql_java_gen (= 0.2.0) x64-mingw32' in any of the gem sources listed in your Gemfile.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.