GRAPHQL Standard Java Implementation Graphql-java Overview __java

Source: Internet
Author: User

GRAPHQL Standard provides a variety of mainstream programming language implementation, this article describes the Java implementation Graphql-java. The implementation of the so-called GRAPHQL standard is the implementation of a GRAPHQL server, through a set of software components to support the request for parsing, validating and executing GRAPHQL queries.

Graphql-java is one of the GRAPHQL standard Java language implementations, and the latest version is currently 8.0. The following are configured in the MAVEN project:

<dependency>
    <groupId>com.graphql-java</groupId>
    <artifactid>graphql-java</ artifactid>
    <version>8.0</version>
</dependency>

This paper mainly introduces the GRAPHQL schema definition of Graphql-java core.

1. GRAPHQL Schema

It is similar to the database server's need to define a database schema in response to user access to the database. The GRAPHQL server, in response to user queries for rest data, also defines a structure that describes the service data, which is the GRAPHQL Schema.

To define the GRAPHQL Schema,graphql-java provides the following two definitions: programmatically defining a dynamic GRAPHQL Schema in code

Graphqlobjecttype Footype = NewObject ()
    . Name ("Ci")
    . Field (Newfielddefinition ()
            . Name ("Product_number ")
            . Type (graphqlstring))
    . Build ();

As the code shows, the new type CI is created in the run, and the property product_number is defined for it, and the property is of type scalar graphqlstring. Define a static graphql Schema in a separate resource file using SDL (Schema definition Language)

Create Src/main/resources/myschema.graphqls file, define type CI as follows:

Type Ci {
    product_number:string
}

Here, for example, the GRAPHQL schema defined in both ways is completely equivalent.

In fact, there are specific syntax for defining the complete GRAPHQL schema, please refer to the Create GRAPHQL schema.

2. Datafetcher/typeresolver

Each field type in the GRAPHQL schema is associated with a datafetcher (called the resolver function in the Node.js implementation or Python implementation) to get data for the field type in the GRAPHQL schema. The data source can be a database or rest service and represent the data as a Java Pojo object. The Datafetcher object can directly read the properties of the Java Pojo object and then use either Jackson or Gson to convert to JSON-formatted data.

Datafetcher pndatafetcher = new Datafetcher () {
    @Override public
    Object Get (datafetchingenvironment Environment) {
        MAP response = fetchpnfromdatabase (Environment.getargument ("Product_number"));
		list<graphqlerror> errors = ((List) response.get ("errors")). Stream ()
			. Map (mymapgraphqlerror::new)
			. Collect (Collectors.tolist ());
		return new Datafetcherresult (Response.get ("Data"), errors);
    }
;
Graphqlobjecttype ObjectType = NewObject ()
        . Name ("Ci")
        . Field (Newfielddefinition ()
                . Name ("Product_ Number ")
                . Type (graphqlstring).
                datafetcher (pndatafetcher))
        . Build ();


Note that the use of the Datafetcher () method here.

Similar to Datafetcher's ability to get data, Typeresolver provides a more powerful capability to convert from the data obtained to the field types defined in the corresponding schema, which is of great significance for interface-oriented programming. In a method of fetching data, the definition of the returned type is an interface, and the actual return may be any object that implements the interface, and can be returned based on the obtained data converted to the corresponding object.

3. Runtime Wiring

Create the GRAPHQL schema is just the beginning and applies it to the GRAPHQL server. This is similar to the SDL script that defines the database structure, but is not effective until it is actually executed on the database server.

The actual execution of the GRAPHQL schema on the GRAPHQL server is done by runtime Wiring, so that an executable GRAPHQL schema can be obtained. The typical code is as follows:

File schemafile = Loadschema ("Myschema.graphqls");

Schemaparser schemaparser = new Schemaparser ();
Typedefinitionregistry typeregistry = Schemaparser.parse (schemafile);

runtimewiring wiring = runtimewiring.newruntimewiring () ... build ();
Schemagenerator schemagenerator = new Schemagenerator ();
Graphqlschema Graphqlschema = Schemagenerator.makeexecutableschema (typeregistry, wiring);

4. GRAPHQL Service

Now that you have a complete graphql Schema to respond to the request, run it.

GRAPHQL build = GRAPHQL.NEWGRAPHQL (Graphqlschema). build ();

5. Execution Request GRAPHQL Service

1) Request parameters

In a request application, you can pass the request parameter directly to the GRAPHQL service as a string, as follows:

ExecutionResult ExecutionResult = Build.execute ("query {hero {name}}");

You can also build the Executioninput object (suitable for complex request parameters) and pass it to the GRAPHQL service as follows:

Executioninput executioninput = Executioninput.newexecutioninput (). Query ("query {hero {name}}")
        . Build ();
ExecutionResult ExecutionResult = Build.execute (executioninput);

2) Processing Results

The response result of the GRAPHQL service is in data, and if an error occurs in the

Executionresult.getdata (). toString ();
list<graphqlerror> errors = Executionresult.geterrors ();

If you want to serialize the resulting response data into JSON format, for full compatibility with the GRAPHQL standard, we recommend that you normalize the response results and then call the JSON libraries such as Jackson or Gson for JSON format conversion.

map<string, object> tospecificationresult = Executionresult.tospecification ();
Dowithjson (Tospecificationresult);

Only synchronous requests are discussed here, and asynchronous requests can refer to their documentation.

Reference Links:

Https://github.com/graphql-java/graphql-java

http://graphql-java.readthedocs.io/en/latest/


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.