kagamihogeの日記

kagamihogeの日記です。

DGS Frameworkのチュートリアルレベルをやる

DGS FrameworkNetflixのGraphQLサーバのためのspring-bootベースのフレームワークhttps://netflix.github.io/dgs/getting-started/チュートリアルをやる。

やったこと

build.gradle

https://start.spring.io/ でベースを作ったあとにチュートリアルのページに書いてある依存性を追加する。

plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation(platform("com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:latest.release"))
    implementation("com.netflix.graphql.dgs:graphql-dgs-spring-boot-starter")

    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

GraphQLのスキーマを追加する。デフォルトではsrc/main/resources/schemaスキーマファイルを作るので、src/main/resources/schema/schema.graphqls を作成する。スキーマの中身はこのチュートリアルではなく https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.graphql.schema からコピペした。

type Query {
    greeting(name: String! = "Spring"): String!
    project(slug: ID!): Project
}

""" A Project in the Spring portfolio """
type Project {
    """ Unique string id used in URLs """
    slug: ID!
    """ Project name """
    name: String!
    """ URL of the git repository """
    repositoryUrl: String!
    """ Current support status """
    status: ProjectStatus!
}

enum ProjectStatus {
    """ Actively supported by the Spring team """
    ACTIVE
    """ Supported by the community """
    COMMUNITY
    """ Prototype, not officially supported yet  """
    INCUBATING
    """ Project being retired, in maintenance mode """
    ATTIC
    """ End-Of-Lifed """
    EOL
}

エントリーポイントのmainを作る。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

スキーマのtypeとenumに対応するデータ入れるためのクラスを作る。

public record Project(String slug, String name, String repositoryUrl, ProjectStatus status) {}

public enum ProjectStatus {
  ACTIVE, COMMUNITY, INCUBATING, ATTIC, EOL
}

queryを実装する。Spring for GraphQLと異なり@Controllerは要らない。

import com.netflix.graphql.dgs.DgsComponent;
import com.netflix.graphql.dgs.DgsQuery;
import com.netflix.graphql.dgs.InputArgument;

@DgsComponent
public class ProjectDataFetcher {
  @DgsQuery
  public String greeting(@InputArgument String name) {
    return "Hello, " + name + "!";
  }

  @DgsQuery
  public Project project(@InputArgument String slug) {
    return new Project(slug, "asdf", "sadf", ProjectStatus.ACTIVE);
  }
}

起動したら http://localhost:8080/graphiql でGraphQLのUIにアクセスできる。

参考URL