🐙

Postman で graphQL をテストする 

に公開

https://zenn.dev/kameoncloud/articles/964d4bb0c0e449
前回の記事で graphQL の簡単な説明を Postman の graphQL クライアントの使い方を解説しました。
graphQL には3つの操作があり、ハンズオンパートではそのうち Query(GET相当) と Mutation(PUT/POST/PATCH/DELETE相当) を試してみました。

今日は3つめSubscription をPostman クライアントで試していきます。

Subscription とは

Query と Mutation はこの2つはクライアントからサーバーへリクエストを送り、レスポンスを受け取るという「リクエスト・レスポンス型」の通信です。

例えば、チャットアプリの新着メッセージや、ダッシュボードのリアルタイム更新など、サーバー側で起きた変化をクライアントに即座に届けたいケースでは、クライアントが何度もリクエストを送って変化を確認する(ポーリング)のはデータのやり取りが行われない非効率な通信が発生します。
そこで登場するのが、GraphQLの3つ目の操作である Subscription です。

Query と Mutation が「クライアントが聞いて、サーバーが答える」モデルだとすれば、Subscription は「クライアントが購読を宣言し、サーバーが変化を通知する」モデルです。
具体的な流れは以下のとおりです。
1.クライアントが「このイベントを購読したい」とサーバーに伝える
2.サーバーとクライアントの間に持続的な接続(WebSocket)が確立される
3.サーバー側でイベントが発生すると、その接続を通じてクライアントにデータが即座にプッシュされる
4.クライアントが購読を解除するか、接続が切れるまでこの状態を維持する

さっそくやってみる

では前回使った package.json と server.jsを以下に変更して起動します。

package.json
{
  "name": "graphql-subscription-server",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@apollo/server": "^5.4.0",
    "@graphql-tools/schema": "^10.0.31",
    "graphql": "^16.12.0",
    "graphql-subscriptions": "^3.0.0",
    "graphql-ws": "^6.0.7",
    "ws": "^8.19.0"
  }
}
server.js
const { createServer } = require("http");
const { ApolloServer } = require("@apollo/server");
const { ApolloServerPluginDrainHttpServer } = require("@apollo/server/plugin/drainHttpServer");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const { WebSocketServer } = require("ws");
const { useServer } = require("graphql-ws/use/ws");
const { PubSub } = require("graphql-subscriptions");

// PubSub インスタンス(イベントの発行・購読を管理)
const pubsub = new PubSub();
const TODO_ADDED = "TODO_ADDED";
const TODO_TOGGLED = "TODO_TOGGLED";
const TODO_DELETED = "TODO_DELETED";

// サンプルデータ
const users = [
  { id: "1", name: "田中太郎", email: "tanaka@example.com", age: 30 },
  { id: "2", name: "佐藤花子", email: "sato@example.com", age: 25 },
  { id: "3", name: "鈴木一郎", email: "suzuki@example.com", age: 35 },
];

let todos = [
  { id: "1", title: "買い物", completed: false, userId: "1" },
  { id: "2", title: "レポート作成", completed: true, userId: "2" },
  { id: "3", title: "ジム", completed: false, userId: "1" },
];

let nextTodoId = 4;

// スキーマ定義
const typeDefs = `#graphql
  type User {
    id: ID!
    name: String!
    email: String!
    age: Int
    todos: [Todo!]!
  }

  type Todo {
    id: ID!
    title: String!
    completed: Boolean!
    user: User
  }

  type Query {
    users: [User!]!
    user(id: ID!): User
    todos: [Todo!]!
    todo(id: ID!): Todo
  }

  type Mutation {
    addTodo(title: String!, userId: ID!): Todo!
    toggleTodo(id: ID!): Todo
    deleteTodo(id: ID!): Boolean!
  }

  # --- Subscription 定義 ---
  type Subscription {
    todoAdded: Todo!
    todoToggled: Todo!
    todoDeleted: ID!
  }
`;

// リゾルバ
const resolvers = {
  Query: {
    users: () => users,
    user: (_, { id }) => users.find((u) => u.id === id),
    todos: () => todos,
    todo: (_, { id }) => todos.find((t) => t.id === id),
  },
  Mutation: {
    addTodo: (_, { title, userId }) => {
      const todo = {
        id: String(nextTodoId++),
        title,
        completed: false,
        userId,
      };
      todos.push(todo);
      // イベントを発行 → Subscriptionに通知
      pubsub.publish(TODO_ADDED, { todoAdded: todo });
      return todo;
    },
    toggleTodo: (_, { id }) => {
      const todo = todos.find((t) => t.id === id);
      if (todo) {
        todo.completed = !todo.completed;
        // イベントを発行 → Subscriptionに通知
        pubsub.publish(TODO_TOGGLED, { todoToggled: todo });
      }
      return todo;
    },
    deleteTodo: (_, { id }) => {
      const len = todos.length;
      todos = todos.filter((t) => t.id !== id);
      if (todos.length < len) {
        // イベントを発行 → Subscriptionに通知
        pubsub.publish(TODO_DELETED, { todoDeleted: id });
        return true;
      }
      return false;
    },
  },
  // --- Subscription リゾルバ ---
  Subscription: {
    todoAdded: {
      subscribe: () => pubsub.asyncIterableIterator([TODO_ADDED]),
    },
    todoToggled: {
      subscribe: () => pubsub.asyncIterableIterator([TODO_TOGGLED]),
    },
    todoDeleted: {
      subscribe: () => pubsub.asyncIterableIterator([TODO_DELETED]),
    },
  },
  User: {
    todos: (parent) => todos.filter((t) => t.userId === parent.id),
  },
  Todo: {
    user: (parent) => users.find((u) => u.id === parent.userId),
  },
};

// サーバー起動
async function main() {
  const schema = makeExecutableSchema({ typeDefs, resolvers });
  const httpServer = createServer();

  // WebSocket サーバー(Subscription用)
  const wsServer = new WebSocketServer({
    server: httpServer,
    path: "/graphql",
  });
  const serverCleanup = useServer({ schema }, wsServer);

  // Apollo Server
  const server = new ApolloServer({
    schema,
    plugins: [
      ApolloServerPluginDrainHttpServer({ httpServer }),
      {
        async serverWillStart() {
          return {
            async drainServer() {
              await serverCleanup.dispose();
            },
          };
        },
      },
    ],
  });

  await server.start();

  // HTTP リクエスト処理(Query/Mutation用)
  httpServer.on("request", async (req, res) => {
    // CORS ヘッダー
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type");

    if (req.method === "OPTIONS") {
      res.writeHead(204);
      res.end();
      return;
    }

    if (req.method === "POST" && req.url === "/graphql") {
      let body = "";
      req.on("data", (chunk) => (body += chunk));
      req.on("end", async () => {
        try {
          const { query, variables, operationName } = JSON.parse(body);
          const result = await server.executeOperation({
            query,
            variables,
            operationName,
          });

          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(result.body.singleResult));
        } catch (e) {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ errors: [{ message: e.message }] }));
        }
      });
      return;
    }

    res.writeHead(404);
    res.end("Not Found");
  });

  httpServer.listen(4000, () => {
    console.log("🚀 Query/Mutation ready at http://localhost:4000/graphql");
    console.log("🔌 Subscription ready at  ws://localhost:4000/graphql");
  });
}

main();
npm install
npm start

> graphql-subscription-server@1.0.0 start
> node server.js

🚀 Query/Mutation ready at http://localhost:4000/graphql
🔌 Subscription ready at  ws://localhost:4000/graphql

ではPostmanのコレクションを新しく作成し以下のクエリーを実行します。接続先はhttp://localhost:4000/graphqlになります。

subscription {
  todoAdded {
    id
    title
    completed
    user { name }
  }
}


これによってPostmanのgraphQLクライアントとserver.jsの間でWebsocketセッションが確立されます。
次にPostmanこれクションのタブをもう一つ開いて、以下を実行します。接続先は同じです。

mutation {
  addTodo(title: "サブスク確認テスト", userId: "1") {
    id
    title
  }
}


これによりテスト用アイテムが一つ追加されます。
先ほどsubscriptionを実行したタブでは、自動で追加されたアイテムの情報を受信しています。

Discussion