HAMADAの語り草

興味のある技術のアウトプットをしたいと思います

学祭ハッカソンの技術まとめ (Apollo Kotlin編)

はじめに

会津大学学部三年のHAMADAです。この記事は「学生iOS&Androidエンジニア Advent Calendar 2023」8日目の記事です。何回かに分けて、学祭ハッカソンで学んだ技術を振り返りたいと思います。今回は、Apollo Kotlinについて綴っていきたいと思います。

アプリの概略

アプリの概略や、ハッカソン自体の記録は以下の記事をご一読いただけると幸いです。

hahahamada.hatenablog.com

ハッカソンでの主な担当部分

  • GraphQLとDynamoDBを用いたバックエンド部分の実装
  • Jetpack ComposeにおけるUI実装
  • クラウドサービスまわり

等々

まとめたいこと

  • Apollo Kotlin を用いた、GraphQL Serverとの繋ぎこみと主な実装
  • GoogleMapAPIを用いた実装
  • Jetpack Composeを用いたUI実装

    //かなり汚くて荒い実装をしたので、設計の勉強のネタとして使いたいですね。

今回説明すること

  • Apollo Kotlin を用いた、GraphQL Serverとの繋ぎこみと主な実装

Apollo Kotlinを用いた、GraphQL Serverとの繋ぎこみと主な実装

Apollo Kotlinは、GraphQLクエリからKotlin、Javaのモデルを生成するGraphQLクライアントです。今回は、Apollo Kotlinを用いて、Goで立てたGraphQLサーバーに対し、ミューテーションやクエリを実行するというものになっています。(DynamoDBを今回使用しているので、GoでGraphQLサーバーを立てずとも、AppSyncを使用した方が筋が良かった気もしています。)

Goで立てた、GraphQLサーバーの実装については以下のリポジトリをご覧ください

https://github.com/ahmos0/ATUMARE_GraphQLServer

github.com

まず、Apollo Kotlinを使用するためにbuild.gradle(:app)に以下を記述します。

plugins{
    //以下を追加
    id 'com.apollographql.apollo3'
}

apollo {
  service("service") {
    packageName.set("com.example.exampleserver")
  }
}

dependecies {
    //以下を追加
    implementation 'com.apollographql.apollo3:apollo-runtime:3.8.2'
}

次に、schema.graphqlsを取得します。

プラグインが自動的に作成するapolloDownloadSchema Gradleを使用して、スキーマを取得します。

以下を実行します。

endpointは任意のものに変更してください。

./gradlew :app:downloadApolloSchema --endpoint='https://hogehoge.com/graphql' --schema=app/src/main/graphql/schema.graphqls

すると以下のような、schema.graphqlsが取得できます。

長いので、折りたたんでおきます。

schema.graphqls

"""
The `Boolean` scalar type represents `true` or `false`.
"""
scalar Boolean

"""
One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.
"""
type __EnumValue {
  deprecationReason: String

  description: String

  isDeprecated: Boolean!

  name: String!
}

"""
Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.
"""
type __InputValue {
  """
  A GraphQL-formatted string representing the default value for this input value.
  """
  defaultValue: String

  description: String

  name: String!

  type: __Type!
}

"""
Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.
"""
type __Field {
  args: [__InputValue!]!

  deprecationReason: String

  description: String

  isDeprecated: Boolean!

  name: String!

  type: __Type!
}

type Mutation {
  putItem(time: String!, capacity: Int!, uuid: String!, name: String!, departure: String!, destination: String!, passenger: Int!,passengers: [PassengerInput]): Item
  incrementPassenger(uuid: String!, name: String!,  passengers: [PassengerInput]): Item
}

input PassengerInput{
  namelist: String!,
  comment: String!
}

"""
The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.

Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.
"""
type __Type {
  description: String

  enumValues("" includeDeprecated: Boolean = false): [__EnumValue!]

  fields("" includeDeprecated: Boolean = false): [__Field!]

  inputFields: [__InputValue!]

  interfaces: [__Type!]

  kind: __TypeKind!

  name: String

  ofType: __Type

  possibleTypes: [__Type!]
}

type Query {
  allItems: [Item]
}

type Item {
  capacity: Int

  departure: String

  destination: String

  name: String

  time: String

  uuid: String

  passenger: Int

  passengers: [PassengerModel]
}

type PassengerModel {
  namelist: String!,
  comment: String!
}

"""
An enum describing what kind of type a given `__Type` is
"""
enum __TypeKind {
  """
  Indicates this type is a list. `ofType` is a valid field.
  """
  LIST

  """
  Indicates this type is a non-null. `ofType` is a valid field.
  """
  NON_NULL

  """
  Indicates this type is a scalar.
  """
  SCALAR

  """
  Indicates this type is an object. `fields` and `interfaces` are valid fields.
  """P
  OBJECT

  """
  Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.
  """
  INTERFACE

  """
  Indicates this type is a union. `possibleTypes` is a valid field.
  """
  UNION

  """
  Indicates this type is an enum. `enumValues` is a valid field.
  """
  ENUM

  """
  Indicates this type is an input object. `inputFields` is a valid field.
  """
  INPUT_OBJECT
}

"""
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
"""
scalar String

"""
The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. 
"""
scalar Int

"""
A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.
"""
type __Schema {
  """
  A list of all directives supported by this server.
  """
  directives: [__Directive!]!

  """
  If this server supports mutation, the type that mutation operations will be rooted at.
  """
  mutationType: __Type

  """
  The type that query operations will be rooted at.
  """
  queryType: __Type!

  """
  If this server supports subscription, the type that subscription operations will be rooted at.
  """
  subscriptionType: __Type

  """
  A list of all types supported by this server.
  """
  types: [__Type!]!
}

"""
A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document. 

In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.
"""
type __Directive {
  args: [__InputValue!]!

  description: String

  locations: [__DirectiveLocation!]!

  name: String!

  onField: Boolean! @deprecated(reason: "Use `locations`.")

  onFragment: Boolean! @deprecated(reason: "Use `locations`.")

  onOperation: Boolean! @deprecated(reason: "Use `locations`.")
}

"""
A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.
"""
enum __DirectiveLocation {
  """
  Location adjacent to an input object field definition.
  """
  INPUT_FIELD_DEFINITION

  """
  Location adjacent to a fragment definition.
  """
  FRAGMENT_DEFINITION

  """
  Location adjacent to a field definition.
  """
  FIELD_DEFINITION

  """
  Location adjacent to an input object type definition.
  """
  INPUT_OBJECT

  """
  Location adjacent to an interface definition.
  """
  INTERFACE

  """
  Location adjacent to a mutation operation.
  """
  MUTATION

  """
  Location adjacent to a schema definition.
  """
  SCHEMA

  """
  Location adjacent to a scalar definition.
  """
  SCALAR

  """
  Location adjacent to an enum value definition.
  """
  ENUM_VALUE

  """
  Location adjacent to a query operation.
  """
  QUERY

  """
  Location adjacent to a fragment spread.
  """
  FRAGMENT_SPREAD

  """
  Location adjacent to an argument definition.
  """
  ARGUMENT_DEFINITION

  """
  Location adjacent to a object definition.
  """
  OBJECT

  """
  Location adjacent to a union definition.
  """
  UNION

  """
  Location adjacent to an enum definition.
  """
  ENUM

  """
  Location adjacent to a subscription operation.
  """
  SUBSCRIPTION

  """
  Location adjacent to a field.
  """
  FIELD

  """
  Location adjacent to an inline fragment.
  """
  INLINE_FRAGMENT
}

"""
Directs the executor to include this field or fragment only when the `if` argument is true.
"""
directive @include ("Included when true." if: Boolean!) on FIELD|FRAGMENT_SPREAD|INLINE_FRAGMENT

"""
Directs the executor to skip this field or fragment when the `if` argument is true.
"""
directive @skip ("Skipped when true." if: Boolean!) on FIELD|FRAGMENT_SPREAD|INLINE_FRAGMENT

"""
Marks an element of a GraphQL schema as no longer supported.
"""
directive @deprecated ("Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formattedin [Markdown](https:\/\/daringfireball.net\/projects\/markdown\/)." reason: String = "No longer supported") on FIELD_DEFINITION|ENUM_VALUE

schema {
  query: Query
  mutation: Mutation
}

これを元に、このスキーマ定義を元に必要なミューテーション、クエリを書きます。

今回、必要な処理は

  • 募集登録画面で情報を登録するミューテーション(PutItem)

  • 募集一覧を取得するクエリ(AllItems)

  • 乗車登録画面から登録した際に、乗員の人数を増やすミューテーション(IncrementPassenger)

  • 運転手待機画面での情報取得(こちらは実装が間に合っていないのでmock画面のみです)

実装はそれぞれ以下

//itemquery.graphql
query AllItems {
    allItems {
        uuid
        name
        departure
        destination
        time
        capacity
        passenger
        passengers {
             namelist,
             comment
        }
    }
}
//mutations.graphql
mutation PutItem($uuid: String!, $name: String!, $departure: String!, $destination: String!, $time: String!, $capacity: Int!, $passenger: Int!, $passengers: [PassengerInput]) {
    putItem(uuid: $uuid, name: $name, departure: $departure, destination: $destination, time: $time, capacity: $capacity, passenger: $passenger, passengers: $passengers) {
        uuid
        name
        departure
        destination
        time
        capacity
        passenger
    }
}

mutation IncrementPassenger($uuid: String!, $name: String!, $passengers:[PassengerInput]) {
    incrementPassenger(uuid: $uuid, name: $name,  passengers: $passengers) {
        uuid
        name
        passengers {
            namelist
            comment
        }
    }
}

これらを定義した後に、プロジェクトをbuildするとプラグインはモデルを生成するために、generateApolloSourcesというタスクを実行します。

これによって、GraphQLクエリ、ミューテーションからkotlinのソースコードが自動生成されます。

その時の名称は、PutItemMutation.kt, IncrementPassengerMutation.kt, AllItemsQuery.ktのように”Mutation” “Query”が末尾についたものとなります。

これらのソースコードを用いた実装が以下になります。

まず、ApolloClientのインスタンスを作成し、送信先のエンドポイントを指定します。

private val apolloClient = ApolloClient.Builder()
        .serverUrl(BuildConfig.serverEndPoint)
        .build()

それぞれのquery, mutationごとの実装は以下になります。

putItem

suspend fun putItem(
        uuid: String,
        name: String,
        departure: String,
        destination: String,
        time: String,
        capacity: Int,
        passenger: Int,
        passengers: List<PassengerInput>? = null
    ): Result<PutItemMutation.PutItem?> {

        val convertedPassengers = passengers?.map { PassengerInput(it.namelist, it.comment) }

        val mutation = PutItemMutation(
            uuid = uuid,
            name = name,
            departure = departure,
            destination = destination,
            time = time,
            capacity = capacity,
            passenger = passenger,
            passengers = convertedPassengers?.let { Optional.Present(it) } ?: Optional.Absent
        )

        return try {
            val call: ApolloCall<PutItemMutation.Data> = apolloClient.mutation(mutation)
            val response: ApolloResponse<PutItemMutation.Data> = call.execute()
            val item = response.data?.putItem
            Result.success(item)

        } catch (e: ApolloException) {
            Result.failure(e)
        }
    }

fetchAllItems

suspend fun fetchAllItems(): Result<List<AllItemsQuery.AllItem>> {
        val query = AllItemsQuery()
        return withContext(Dispatchers.IO) {
            try {
                val response: ApolloResponse<AllItemsQuery.Data> = apolloClient.query(query).execute()
                Result.success(response.data?.allItems?.filterNotNull() ?: emptyList())
            } catch (e: ApolloException) {
                Result.failure(e)
            }
        }
    }

incrementPassenger

suspend fun incrementPassenger(uuid: String, name: String, namelist: String,comment: String) {
        val newPassengerInput = PassengerInput(namelist, comment)
        val passengerInputList = listOf(newPassengerInput)
        val mutation = IncrementPassengerMutation(uuid, name, Optional.Present(passengerInputList))

        try {
            val call: ApolloCall<IncrementPassengerMutation.Data> = apolloClient.mutation(mutation)
            call.execute()
            Result.success(Unit)
        } catch (e: ApolloException) {
            Result.failure(e)
        }
    }

これらを対応した画面から呼び出すことで、GraphQLサーバーを通したDBとのやりとりを実現しました。

感想と展望

そもそもGraphQLの実装部分で苦労しましたが、なんとか動くように実装できました。やはり、公式ドキュメントをしっかり読むことは大事だなと再確認できました。バックエンドとクライアント部分の両方に取り組んで実装できたことは、すごく大きな経験になりました。GoogleMapAPI周りでも詰まったところがあったので、近いうちにまとめたいと思います。コードがかなり稚拙ではありますが、何かの参考になれば幸いです。ここまで読んでいただきありがとうございます。

所属サークル

https://twitter.com/aizu_PxL

私のTwitter

https://twitter.com/AHMOS_HMD

私のgithub

ahmos0 (HAMADA) · GitHub

参考リンク

www.apollographql.com