☁️

openapi-typescript + msw でモックハンドラのユーティリティを作る

に公開

orvalに乗り換えようか試していたところ、エラー系統(2XX以外)のモックハンドラがうまく生成されなそうだったので、自前で作ったやつをメモ。
application/jsonのレスポンスに絞って実装。

型まわり
import type {
  HttpMethod,
  ErrorStatus,
  OkStatus,
} from "openapi-typescript-helpers";

import type { paths } from "@/__api__/generated/openapi-typescript";

export type APIPath = keyof paths;

/**
 * パスのメソッドを取得する
 * @param P paths[P]
 */
export type APIMethod<P> = {
  [K in Extract<keyof P, HttpMethod>]: P[K] extends undefined ? never : K;
}[Extract<keyof P, HttpMethod>];

export type APIResponse<
  P extends APIPath,
  M extends HttpMethod,
> = paths[P][M] extends {
  responses: infer U;
}
  ? U
  : never;

type NumericOkStatus = Extract<OkStatus, number>;
type NumericErrorStatus = Extract<ErrorStatus, number>;
export type APIStatusCode<
  P extends APIPath,
  M extends APIMethod<paths[P]>,
> = keyof APIResponse<P, M> extends number
  ? Extract<keyof APIResponse<P, M>, NumericOkStatus | NumericErrorStatus>
  : never;

/**パスパラメータ */
export type MockAPIPathParameters<
  T,
  K extends Extract<keyof T, HttpMethod>,
> = T[K] extends { parameters: { path: infer U } }
  ? unknown extends U
    ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Record<any, any>
    : U
  : never;

/**クエリパラメータ */
export type MockAPIQueryParameters<
  T,
  K extends Extract<keyof T, HttpMethod>,
> = T[K] extends { parameters: { query?: infer U } }
  ? unknown extends U
    ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Record<any, any>
    : U
  : never;

/**レスポンスコンテンツ */
export type MockAPIResponseContentJson<
  T,
  K extends Extract<keyof T, HttpMethod>,
  C extends NumericOkStatus | NumericErrorStatus = NumericOkStatus,
> = T[K] extends {
  responses: { [key in C]?: { content: { "application/json": infer U } } };
}
  ? unknown extends U
    ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Record<any, any>
    : U
  : never;

/**リクエストボディ */
export type MockAPIRequestBody<
  T,
  K extends Extract<keyof T, HttpMethod>,
> = T[K] extends {
  requestBody: { content: { "application/json": infer U } };
}
  ? unknown extends U
    ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Record<any, any>
    : U
  : never;

handler
import {
  http,
  HttpResponse,
  type HttpResponseResolver,
  delay as delayFn,
} from "msw";

import type {
  MockAPIPathParameters,
  MockAPIRequestBody,
  MockAPIResponseContentJson,
} from "./type";
import type { APIPath, APIMethod, APIStatusCode } from "./type";

import type { paths } from "@/__api__/generated/openapi-typescript";

// 中括弧をコロンに変換
const parsePathFromCurlyBracesToColon = (path: string) => {
  return path.replace(/{/g, ":").replace(/}/g, "");
};

export const createMockApiHandler = <
  T extends APIPath,
  M extends APIMethod<paths[T]>,
  C extends APIStatusCode<T, M>,
>(
  path: T,
  method: M,
  status: C,
  _handler:
    | HttpResponseResolver<
        MockAPIPathParameters<paths[T], M>,
        MockAPIRequestBody<paths[T], M>,
        MockAPIResponseContentJson<paths[T], M, C>
      >
    | MockAPIResponseContentJson<paths[T], M, C>,
  options: {
    delay?: number;
  } = {
    delay: 1500,
  }
) => {
  const { delay } = options;
  const handler: HttpResponseResolver<
    MockAPIPathParameters<paths[T], M>,
    MockAPIRequestBody<paths[T], M>,
    MockAPIResponseContentJson<paths[T], M, C>
  > = async (...args) => {
    if (delay) {
      await delayFn(delay);
    }

    if (typeof _handler === "function") {
      return _handler(...args);
    }

    return HttpResponse.json(_handler, { status });
  };

  if (method === "get") {
    return http.get<
      MockAPIPathParameters<paths[T], M>,
      MockAPIRequestBody<paths[T], M>,
      MockAPIResponseContentJson<paths[T], M, C>
    >(`*${parsePathFromCurlyBracesToColon(path)}`, handler);
  }
  if (method === "post") {
    return http.post<
      MockAPIPathParameters<paths[T], M>,
      MockAPIRequestBody<paths[T], M>,
      MockAPIResponseContentJson<paths[T], M, C>
    >(`*${parsePathFromCurlyBracesToColon(path)}`, handler);
  }
  if (method === "put") {
    return http.put<
      MockAPIPathParameters<paths[T], M>,
      MockAPIRequestBody<paths[T], M>,
      MockAPIResponseContentJson<paths[T], M, C>
    >(`*${parsePathFromCurlyBracesToColon(path)}`, handler);
  }
  if (method === "delete") {
    return http.delete<
      MockAPIPathParameters<paths[T], M>,
      MockAPIRequestBody<paths[T], M>,
      MockAPIResponseContentJson<paths[T], M, C>
    >(`*${parsePathFromCurlyBracesToColon(path)}`, handler);
  }
  if (method === "patch") {
    return http.patch<
      MockAPIPathParameters<paths[T], M>,
      MockAPIRequestBody<paths[T], M>,
      MockAPIResponseContentJson<paths[T], M, C>
    >(`*${parsePathFromCurlyBracesToColon(path)}`, handler);
  }
  throw new Error("Invalid method");
};


以下の感じで使えます。補完も効きます。


const successHandler = createMockApiHandler("/v1/user/me", "get", 200, {
    userName: "marromugi"
})

// リクエストベースでゴニョゴニョする
const dynamicHandler = createMockApiHandler("/v1/user/me", "patch", 200, async ({ request }) => {
    const data = (await request.json()) as { userName: string };
    return HttpResponse.json(
      {
        userName: data.userName,
      } as const,
      {
        status: 200,
      }
    );
})

// 他のステータス(ex. OAS上で定義した401レスポンス)
const badRequestHandler = createMockApiHandler("/v1/user/me", "get", 401, {
    message: "Unauthorized"
})

Discussion