How to integrate GraphQL in the Microservice

Reading Time: 4 minutes

GraphQL is a query language for your APIs and a runtime for fulfilling those queries with existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more. GraphQL is designed to make APIs fast, flexible, and developer-friendly.

GraphQL SPQR

GraphQL SPQR (GraphQL Schema Publisher & Query Resolver, pronounced like speaker) is a simple-to-use library for rapid development of GraphQL APIs in Java. It works by dynamically generating a GraphQL schema from Java code.

In this tutorial, we are going to explain simple steps for how to integrate Graphql in your microservice.

  • Include dependencies in pom.xml
<!-- GraphQL -->
<dependency>
    <groupId>io.leangen.graphql</groupId>
    <artifactId>spqr</artifactId>
    <version>${graphql-spqr.version}</version>
</dependency>
<dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-spring-boot-autoconfigure</artifactId>
    <version>${graphql-spring-boot-autoconfigure.version}</version>
</dependency>
  • Spring Boot Java Configuration class:
@Configuration
public class GraphQLConfiguration {
    @Bean
    public GraphQLSchema schema(GraphQLRootQuery graphQLRootQuery,
                                GraphQLRootMutation graphQLRootMutation,
                                GraphQLRootSubscription graphQLRootSubscription,
                                GraphQLResolvers graphQLResolvers) {
        GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withBasePackages("com.myproject.microservices")
            .withOperationsFromSingletons(graphQLRootQuery, graphQLRootMutation, graphQLRootSubscription, graphQLResolvers)
            .generate();
        return schema;
    }

    @Bean
    public GraphQLResolvers resolvers(MyOtherMicroserviceClient myOtherMicroserviceClient) {
        return new GraphQLResolvers(myOtherMicroserviceClient);
    }

    @Bean
    public GraphQLRootQuery query(MyOtherMicroserviceClient myOtherMicroserviceClient) {
        return new GraphQLRootQuery(myOtherMicroserviceClient);
    }

    @Bean
    public GraphQLRootMutation mutation(MyOtherMicroserviceClient myOtherMicroserviceClient) {
        return new GraphQLRootMutation(myOtherMicroserviceClient);
    }

    // define your own scalar types (custom data type) if you need to.
    @Bean
    public GraphQLEnumProperty graphQLEnumProperty() {
        return new GraphQLEnumProperty();
    }

    @Bean
    public JsonScalar jsonScalar() {
        return new JsonScalar();
    }

    /* Add your own custom error handler if you need to.
    This is needed, if you want to propagate any custom information error messages propagated to the client. */
    @Bean
    public GraphQLErrorHandler errorHandler() {
        ....
    }

}
  • GraphQL class for query operations:
public class GraphQLRootQuery {

    @GraphQLQuery(description = "Retrieve list of your attributes by search criteria")
    public List<AttributeDTO> getMyAttributes(@GraphQLId @GraphQLArgument(name = "id", description = "Id of your attribute") String id,
                                              @GraphQLArgument(name = " myQueryParam ", description = "…") String myQueryParam) {
        return …;
    }
}
  • GraphQL class for mutation operations:
public class GraphQLRootMutation {

    @GraphQLMutation(description = "Update attribute")
    public AttributeDTO updateAttribute(@GraphQLId @GraphQLNonNull @GraphQLArgument(name = "id", description = "Id of your attribute") String id,
                                        @GraphQLArgument(name = "payload", description = "Payload for update") UpdateRequest payload) {
        return …
    }
}
  • GraphQL resolvers:
public class GraphQLResolvers {

    @GraphQLQuery(description = "Retrieve additional information")
    public List<AdditionalInfoDTO> getAdditionalInfo(@GraphQLContext AttributesDTO attributesDTO) {
        return …
    }
}

Note: All the Java classes (AdditionalInfoDTO, AttributesDTO, UpdateRequest) are just examples for data transfer objects and requests that needs to be replaced with your custom classes in order the code to compile and be executable.

  • How to use GraphQL from client side?

Finally, we want to have a look, how GraphQL looks from the front end side. We are using a tool, called  GraphiQL (https://www.electronjs.org/apps/graphiql) to test it.

  • GraphQL Endpoint: URL of your service, defaults to /graphql
  • Method: it is always POST
  • HTTP Header: You can include authorization tokens with the request
  • Left pane: the query, must be always in JSON format
  • Right pane: response from the server, always JSON
  • Note: You get what you request, only those attribute are returned which you request.

Simple examples for query and mutation:

In this tutorial, you learned how to create your GraphQL API in Java with Spring Boot. But you are not limited to Spring Boot for that. You can use the GraphQL SPQR in pretty much any Java environment.

The way to the professional VueJS-Project ( Part 1 )

Reading Time: 4 minutes

Okay, it’s usually easy to start a VueJS project. There are many tutorials or Vue-Cli templates and with the Vue-Cli 3.x, it’s super easy to create your own. Here are some links:

BUT what if the requirements increase and become more demanding? Or if component/functional testing and typification are required? Or “newer” technologies such as GraphQL, serverless, state machines/diagrams and module dependency management come into play?

How to start?

We’ll start with the easiest way and use the VueCli API.

# via console
vue create professional-world
# or via the vue cli gui
vue ui

We will be prompted to pick a preset. First, select manually features.

After we select these features, we will choose the following setup.

Some points about our setup:

  • class-style
    I choose this mode to show you the TypeScript decorator for class-style Vue components. But of course, you can take the normal style it is not so many new stuff for the first time.
  • history mode
    We do not choose this router mode, because for a simpler environment setup. If you don’t like this – feel free to change this. Read more about it here.
  • css pre-processor
    You can choose whatever you want. I prefer stylus regarding the less code. 😏
  • lintner
    It makes sense to activate here TSLint and also the auto-fix on commit. But we will add husky instead of a git-hook.
  • cypress vs nightwatch
    We choose cypress because it has some nice other testing features e.g. debuggability, automatic waiting, network traffic control, spies, stubs, clocks and screenshots and videos testing. But we will pay for it with the limited browser compatibility at the moment – later we will close this gap with regression tests.
  • config placing
    I prefer to use in dedicated config files. It is easier to change and also the package.json is more readable if you add more dependencies.

Now we will add some more dependencies before we can start:

yarn add -D husky vue-cli-plugin-pug eslint-plugin-pug jest-image-snapshot
  • husky
    It makes git hooks easy
  • pug
    It’s a robust, elegant, feature-rich template engine for Node.js
  • jest-image-snapshot
    It’s a jest matcher for image comparisons. Most commonly used for visual regression testing.

Last configurations

Husky needs to add the following file.huskyrc.js (If you want you can delete the links for the git-hook in the package.json😎

module.exports = {
  "hooks": {
    "pre-commit": "lint-staged"
  }
}

For pug, we add a vue plugin and also an eslint plugin. Eslint itself needs the following configuration in tslint.json.

"plugins": [ "pug" ],

Start coding

After this configurations we can start coding ☺️ Ok we start first with refactoring the example files from the Vue-Cli template to pug syntax. You can use for this a formatter e.g. html-to-pug.com.

Extra tipp

Create a new file named .editorconfig and add following content. It helps you with keep the coding style – you do not need to worry about the format.

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

After this you should have this status from your project:
https://gitlab.com/47northlabs/public/a-professional-vue-world/tree/part-1

Following parts

  • Coding with typescript, stylus and pug ( Part 2 )
  • First steps with unit component, functional and e2e tests ( Part 3 )
  • Vue and VueX meets state machines ( Part 4 )
  • Apollo/GraphQL with serverless services ( Part 5 )
  • Module dependency management in VUE ( Part 6 )