Spring Boot GraphQL WebSocketGraphQlTester

Spring Boot GraphQL supports HTTP API, which is a unidirectional request-response mechanism, the client request and server returns it's corresponding response and endpoint is closed, to retrieve another response, a new HTTP API request needs to be raised by the client.

On the other hand, a websocket is a biderection, stateful, fully duplex protocall, which keeps the connection open until the response data is transmitted successfully or either client or server closes the connection.

package org.wesome.graphql.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.graphql.data.method.annotation.SubscriptionMapping;
import org.springframework.stereotype.Controller;
import org.wesome.graphql.entity.Apple;
import org.wesome.graphql.service.AppleService;
import reactor.core.publisher.Flux;

@Controller
public class AppleGraphQLController {
    @Autowired
    private AppleService appleService;

    @SubscriptionMapping("appleSubscribe")
    public Flux<Apple> appleSubscribe() {
        return appleService.findLatest();
    }
}
package org.wesome.graphql.data;

public enum AppleName {
    MACINTOSH("Macintosh"),
    FUJI("Fuji"),
    GALA("Gala"),
    JONAGOLD("Jonagold");
    private String appleName;

    AppleName(String appleName) {
        this.appleName = appleName;
    }
}
package org.wesome.graphql.entity;

public record Apple(int appleId, String appleName, Float price, Boolean available, String time) {
}
package org.wesome.graphql.service;

import org.wesome.graphql.entity.Apple;
import reactor.core.publisher.Flux;

public interface AppleService {
    Flux<Apple> findLatest();
}
package org.wesome.graphql.service;

import com.github.javafaker.Faker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wesome.graphql.data.AppleName;
import org.wesome.graphql.entity.Apple;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class AppleServiceImpl implements AppleService {
    @Autowired
    private Faker faker;

    @Override
    public Flux<Apple> findLatest() {
        List<Apple> collect = IntStream.rangeClosed(0, AppleName.values().length - 1).mapToObj(value -> new Apple(value, AppleName.values()[value].name(), Float.valueOf(value), faker.random().nextBoolean(), LocalTime.now().toString())).collect(Collectors.toList());
        return Flux.fromIterable(collect).delayElements(Duration.ofSeconds(2));
    }
}
package org.wesome.graphql;

import com.github.javafaker.Faker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class GraphqlProjectApplication {
    public static void main(String[] args) {
        SpringApplication.run(GraphqlProjectApplication.class, args);
    }

    @Bean
    public Faker getFaker() {
        Faker faker = new Faker();
        return faker;
    }
}

\src\main\resources\application.properties

spring.graphql.graphiql.enabled=true
spring.graphql.websocket.path=/graphql

\src\main\resources\graphql\schema.graphqls

# Apple Object
type Apple{
    # primary key of apple
    appleId:ID!
    # apple Name
    appleName:String
    # apple price
    price:Float
    # apple Availability
    available:Boolean
    # current time
    time:String
}

# Apple Query
type Query{
    # query to get all apples
    apples:[Apple]
}

# Apple Subscription
type Subscription {
    appleSubscribe:Apple
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.5</version>
        <relativePath/>
    </parent>
    <groupId>org.wesome</groupId>
    <artifactId>spring-boot-graphql</artifactId>
    <version>0.0.1-snapshot</version>
    <name>spring-boot-graphql</name>
    <description>implementing graphql in spring boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.graphql</groupId>
            <artifactId>spring-graphql-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

\src\test\resources\graphql-test\apples.graphql 

subscription AppleSubscribe {
    appleSubscribe {
        appleId
        appleName
        price
        available
        time
    }
}
package org.wesome.graphql.controllers;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.test.tester.GraphQlTester;
import org.springframework.graphql.test.tester.WebSocketGraphQlTester;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.wesome.graphql.entity.Apple;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

import java.net.URI;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertNotNull;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AppleGraphQLWebSocketTest {
    GraphQlTester graphQlTester;
    @Value("http://localhost:${local.server.port}${spring.graphql.websocket.path}")
    private String baseUrl;

    @BeforeEach
    void setUp() {
        URI url = URI.create(baseUrl);
        this.graphQlTester = WebSocketGraphQlTester.builder(url, new ReactorNettyWebSocketClient()
        ).build();
    }

    @Test
    void appleSubscribe() {
        Flux<Apple> appleResponse = graphQlTester
                .documentName("appleSubscribe")
                .executeSubscription()
                .toFlux("appleSubscribe", Apple.class);
        StepVerifier
                .create(appleResponse)
                .expectSubscription()
                .consumeSubscriptionWith(
                        apple -> assertAll(() -> assertNotNull(apple, "apple object should not be null")))
                .thenCancel().verify();
    }
}

GraphiQL

GraphQL provides an inbuild UserInterface GraphiQL, which can be accessed via http://localhost:8080/graphiql or access GraphQL via Postmanin the query section add the below query

subscription AppleSubscribe {
    appleSubscribe {
        appleId
        appleName
        price
        available
        time
    }
}

follow us on