GraphQLサーバーからクライアントへのスキーマ同期にCircleCIを使ってみた

モチベーション

GraphQLサーバーとクライアント間ではスキーマを共有する必要がある。自動化したい。

つくったもの

CircleCIのワークフロー実行時にlocalhostでGraphQLサーバーを立てて、Apollo CLI経由でサーバーからスキーマを取得する。取得したスキーマをクライアントのリポジトリにpushする。

ざっくり構成図

コード

version: 2.1

jobs:
  dispatch-schema-to-client:
    docker:
      - image: cimg/go:1.18.4
    steps:
      - checkout
      - run:
          command: go run server.go
          background: true
      - run:
          name: "install npm (node.js)"
          command: |
            curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
            sudo apt install -y nodejs
      - run: npm install apollo
      - run: npx apollo service:download --endpoint http://localhost:8080/query
      - add_ssh_keys:
          fingerprints:
            - "xxx"
      - run:
          name: "commit schema.json to client repository"
          command: |
            git clone https://${GITHUB_PERSONAL_ACCESS_TOKEN}@github.com/{USERNAME}/{REPOSITORY}
            mv schema.json {PATH}/schema.json
            cd {REPOSITORY}
            git config user.email ${GITHUB_EMAIL}
            git config user.name "xxx"
            git checkout -b test-circleci
            git add {PATH}/schema.json
            git commit -m '[CircleCI] update schema.json'
            git push origin HEAD:develop

workflows:
  dispatch-schema-to-client:
    jobs:
      - dispatch-schema-to-client

git周りが人力感がある。
以下ポイント。

runのバックグラウンド実行

- run:
    command: go run server.go
    background: true

素直にバックグラウンド実行をさせたい場合は <command> & のようにアンパサンドを置くのだがCircleCIでは機能しない。代わりにrunのbackgroundをtrueにする必要がある。

npmのインストール

- run:
    name: "install npm (node.js)"
    command: |
        curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
        sudo apt install -y nodejs

ApolloCLIを使うにはnpmが必要で、npmをコマンド経由でインストールする必要があった。コマンド経由でインストールする公式なドキュメントが見当たらず困っていたがnodesource/distributionsを参考にしたらできた。orb経由にしたい。

今後の展望

上記の設定ファイルだと差分がない時に失敗するので、差分がない時点でワークフローを成功扱いで終了させたい。

参考