0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

msw+expressでGraphQL APIのモックサーバを建てる

Posted at

以下のGQLクエリに対してレスポンスするモックサーバを建てたい

query tasks {
  tasks {
    collection {
      id
      name
      description
      startAt
      endAt
    }
  }
}

サーバの実装は以下。

faker, msw, @mswjs/http-middleware, express, corsは事前に全部npmでインストールしておく必要あり。

import { faker } from "@faker-js/faker";
import { createMiddleware } from "@mswjs/http-middleware";
import cors from "cors";
import express from "express";
import { HttpResponse, graphql } from "msw";

const buildMockTask = () => {
  // mockのstartAt/endAtが正しい前後関係になるようにfakerで値を生成する
  const from = faker.date.anytime();
  const to = faker.date.future({ refDate: from });

  return {
    id: faker.string.uuid(),
    name: faker.lorem.words(),
    description: faker.lorem.paragraph(1),
    startAt: from,
    endAt: to,
  };
};

const handlers = [
  graphql.query("tasks", () => {
    return HttpResponse.json({
      data: {
        tasks: {
          // とりあえず5個生成しておく。
          collection: Array.from({ length: 5 }).map(() => buildMockTask()),
        },
      },
    });
  }),
];

const app = express();

app.use(
  cors({
    origin: [
      // ここは必要に応じて許可したいホストを追加する
      "http://localhost:4500", 
      "http://localhost:3000",
    ],
    credentials: true,
  }),
);
app.use(express.json());
app.use(createMiddleware(...handlers));
app.listen(8000, () => {
  console.log("running mock server...");
});

@mswjs/http-middlewarecreateServer というインターフェイスを提供しているのでexpressがなくても良いはずだがTypeScriptの型定義周りにバグがあり、それをts-ignoreで無視して動かそうとするとうまくうごかなかった。

あと結局CORS周りを考慮するならmiddlewareとして扱った方がいい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?