Skip to content

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

License

Notifications You must be signed in to change notification settings

constantind/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.0.0</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>5.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.

Configuration Options

All plugin configuration properties and their defaults:

<configuration>
    <services>
        <!--Complete default configuration-->
        <lahzouz-complete-api>
            <enabled>true</enabled>
            <addSourceRoot>true</addSourceRoot>
            <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>
                <operationOutputFile>
                    ${project.build.directory}/generated/operationOutput/apollo/lahzouz/operationOutput.json
                </operationOutputFile>
                <generateOperationDescriptors>false</generateOperationDescriptors>
                <compilerParams>
                    <rootFolders>
                        <rootFolder>${project.basedir}/src/main/graphql/lahzouz/</rootFolder>
                    </rootFolders>
                    <customScalarsMapping></customScalarsMapping>
                    <operationIdGeneratorClass></operationIdGeneratorClass>
                    <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>
                    <moduleName>apollographql</moduleName>
                    <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>
    ...
    <customScalarsMapping>
        <Long>java.time.LocalDate</Long>
    </customScalarsMapping>
    ...
</configuration>

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

public class DateGraphQLAdapter implements Adapter<Date> {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Date fromJson(@NotNull final JsonReader jsonReader, @NotNull final CustomScalarAdapters customScalarAdapters) throws IOException {
        try {
            return DATE_FORMAT.parse(jsonReader.nextString());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void toJson(@NotNull final JsonWriter jsonWriter, @NotNull final CustomScalarAdapters customScalarAdapters, final Date date) throws IOException {
        jsonWriter.value(DATE_FORMAT.format(date));
    }
}

Using Apollo Client

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Kotlin 98.3%
  • Shell 1.7%