Skip to content

Generate a Java/Kotlin GraphQL client based on introspection data and predefined queries.

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE
MIT
COPYING
Notifications You must be signed in to change notification settings

aoudiamoncef/apollo-client-maven-plugin

 
 

Repository files navigation

Apollo GraphQL Client Code Generation Maven Plugin

Build Status Download Known Vulnerabilities License: MIT

Maven plugin that calls the Apollo Kotlin compiler to generate your Java/Kotlin sources.

Usage

Apollo 2 support

Getting Started

  1. Add the apollo runtime library to your project’s dependencies:

    <dependencies>
       <dependency>
           <groupId>com.apollographql.apollo3</groupId>
           <artifactId>apollo-runtime</artifactId>
           <version>3.8.2</version>
       </dependency>
    </dependencies>
  2. Add the code generator plugin to your project’s build:

    <plugins>
        <plugin>
            <groupId>com.github.aoudiamoncef</groupId>
            <artifactId>apollo-client-maven-plugin</artifactId>
            <version>7.0.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <services>
                            <example-api>
                                <compilationUnit>
                                    <name>example</name>
                                    <compilerParams>
                                        <schemaPackageName>com.example.graphql.client</schemaPackageName>
                                    </compilerParams>
                                </compilationUnit>
                            </example-api>
                        </services>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
  3. Create a file src/main/graphql/SERVICE_NAME/schema.json with the JSON results of an introspection query, OR you can automatically generate this file by setting introspection.enabled to true and endpointUrl to your GraphQL endpoint. At build time, the plugin will query the server and install this file per the value of schemaFile.

  4. Create files for each query you’d like to generate classes for under src/main/graphql/SERVICE_NAME:

    1. Query file names must match the name of the query they contain

    2. Query files must end with .graphql OR .gql by default.

    3. Any subdirectories under src/main/graphql/SERVICE_NAME are treated as extra package names to append to schemaPackageName in the plugin config.

  5. Run mvn generate-sources to generate classes for your queries.

  6. If you run into compilation issues such as package com.apollographql.apollo3.api does not exist, you may need to explicitly add the following runtime libraries to your pom.xml

    ---
    <dependency>
          <groupId>com.apollographql.apollo3</groupId>
          <artifactId>apollo-api-jvm</artifactId>
          <version>3.8.2</version>
    </dependency>
     <dependency>
        <groupId>com.apollographql.apollo3</groupId>
        <artifactId>apollo-runtime-jvm</artifactId>
        <version>3.8.2</version>
    </dependency>
    ---

Configuration Options

All plugin configuration properties and their defaults:

<configuration>
    <services>
        <!--Complete default configuration-->
        <lahzouz-complete-api>
            <enabled>true</enabled>
            <addSourceRoot>true</addSourceRoot>
            <addTestSourceRoot>false</addTestSourceRoot>
            <sourceFolder>${project.basedir}/src/main/graphql/lahzouz</sourceFolder>
            <schemaPath>${project.basedir}/src/main/graphql/lahzouz/schema.json</schemaPath>
            <includes>
                <include>**/*.graphql</include>
                <include>**/*.gql</include>
                <include>**/*.json</include>
                <include>**/*.sdl"</include>
            </includes>
            <excludes></excludes>
            <compilationUnit>
                <name>lahzouz</name>
                <outputDirectory>
                    ${project.build.directory}/generated-sources/graphql-client/lahzouz/
                </outputDirectory>
                <testDirectory>
                    ${project.build.directory}/generated-sources/graphql-client/lahzouz/test/
                </testDirectory>
                <debugDirectory>
                    ${project.build.directory}/generated-sources/graphql-client/lahzouz/debug/
                </debugDirectory>
                <generateOperationDescriptors>false</generateOperationDescriptors>
                <compilerParams>
                    <rootFolders>
                        <rootFolder>${project.basedir}/src/main/graphql/lahzouz/</rootFolder>
                    </rootFolders>
                    <scalarsMapping></scalarsMapping>
                    <operationIdGeneratorClass></operationIdGeneratorClass>
                    <operationManifestFormat>persistedQueryManifest</operationManifestFormat>
                    <schemaPackageName>com.lahzouz.apollo.graphql.client</schemaPackageName>
                    <packageName>com.lahzouz.apollo.graphql.client</packageName>
                    <codegenModels>OPERATION</codegenModels>
                    <flattenModels>true</flattenModels>
                    <generateApolloMetadata>false</generateApolloMetadata>
                    <generateAsInternal>false</generateAsInternal>
                    <generateFilterNotNull>false</generateFilterNotNull>
                    <generateFragmentImplementations>false</generateFragmentImplementations>
                    <generateKotlinModels>false</generateKotlinModels>
                    <generateOptionalOperationVariables>false</generateOptionalOperationVariables>
                    <generateQueryDocument>true</generateQueryDocument>
                    <generateResponseFields>false</generateResponseFields>
                    <generateSchema>false</generateSchema>
                    <generateTestBuilders>false</generateTestBuilders>
                    <generateDataBuilders>false</generateDataBuilders>
                    <generateModelBuilders>false</generateModelBuilders>
                    <nullableFieldStyle>NONE</nullableFieldStyle>
                    <useSemanticNaming>true</useSemanticNaming>
                    <targetLanguage>JAVA</targetLanguage>
                    <sealedClassesForEnumsMatching></sealedClassesForEnumsMatching>
                    <alwaysGenerateTypesMatching></alwaysGenerateTypesMatching>
                    <metadataOutputFile>
                        ${project.build.directory}/generated/metadata/apollo/lahzouz/metadata.json
                    </metadataOutputFile>
                </compilerParams>
            </compilationUnit>
            <introspection>
                <enabled>false</enabled>
                <endpointUrl></endpointUrl>
                <headers></headers>
                <schemaFile>${project.basedir}/src/main/graphql/lahzouz/schema.json</schemaFile>
                <connectTimeoutSeconds>10</connectTimeoutSeconds>
                <readTimeoutSeconds>10</readTimeoutSeconds>
                <writeTimeoutSeconds>10</writeTimeoutSeconds>
                <useSelfSignedCertificat>false</useSelfSignedCertificat>
                <useGzip>false</useGzip>
                <prettyPrint>false</prettyPrint>
            </introspection>
        </lahzouz-complete-api>

        <!--Minimal configuration-->
        <lahzouz-min-api>
            <compilationUnit>
                <name>lahzouz</name>
            </compilationUnit>
        </lahzouz-min-api>

        <!--Auto configuration-->
        <lahzouz></lahzouz>
    </services>
</configuration>

Custom Types

To use custom Scalar Types you need to define mapping configuration then register your custom adapter:

<configuration>
    ...
    <scalarsMapping>
        <Long>java.time.LocalDate</Long>
    </scalarsMapping>
    ...
</configuration>

Implementation of a custom adapter for java.time.LocalDate:

import com.apollographql.apollo3.api.Adapter;
import com.apollographql.apollo3.api.CustomScalarAdapters;
import com.apollographql.apollo3.api.json.JsonReader;
import com.apollographql.apollo3.api.json.JsonWriter;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateGraphQLAdapter implements Adapter<LocalDate> {
    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_DATE;

    @Override
    public LocalDate fromJson(@NotNull final JsonReader reader, @NotNull final CustomScalarAdapters customScalarAdapters) throws IOException {
        String dateString = reader.nextString();
        return LocalDate.parse(dateString, dateFormatter);
    }

    @Override
    public void toJson(@NotNull final JsonWriter writer, @NotNull final CustomScalarAdapters customScalarAdapters, final LocalDate value) throws IOException {
        writer.value(value.format(dateFormatter));
    }
}
<configuration>
    ...
    <scalarsMapping>
        <Date>
            <targetName>java.time.LocalDate</targetName>
            <expression>new com.example.LocalDateGraphQLAdapter()</expression>
        </Date>
    </scalarsMapping>
    ...
</configuration>

Test Sources

To generate sources for tests:

<configuration>
    ...
    <addSourceRoot>false</addSourceRoot>
    <addTestSourceRoot>true</addTestSourceRoot>
    <compilationUnit>
        <name>example</name>
        <outputDirectory>${project.basedir}/target/generated-test-sources/apollo/example</outputDirectory>
        <debugDirectory>${project.basedir}/target/generated-test-sources/apollo/example/debug</debugDirectory>
        <testDirectory>${project.basedir}/target/generated-test-sources/apollo/example/debug</testDirectory>
    <compilationUnit/>
    ...
</configuration>

Using Apollo Client