Skip to content

Instantly share code, notes, and snippets.

@harada-shota
Created November 30, 2021 00:56
Show Gist options
  • Save harada-shota/005e579ac941789deec1308cabac97c6 to your computer and use it in GitHub Desktop.
Save harada-shota/005e579ac941789deec1308cabac97c6 to your computer and use it in GitHub Desktop.
// .msw/handler.ts
import { rest } from "msw";
import parsePreferHeader from "parse-prefer-header";
import { endpoints, OpenAPISpec } from "./openAPISpec";
import { OpenAPISpecTools } from "./openAPIUtils";
export function getHandlers(openAPISpec: OpenAPISpec) {
const openAPISpecTools = new OpenAPISpecTools(openAPISpec);
return endpoints
.map((endpoint) => {
return openAPISpecTools.getMethodsBy(endpoint).map((method) => {
// mswとopenapiでpath parameterの指定方法が違うため置換している
const requestPath = endpoint
.replace(/{.*}/g, ":$&")
.replace(/[{,}]/g, "");
return rest.get(`${requestPath}`, (_req, res, ctx) => {
const exampleNames =
openAPISpecTools.getExampleNamesBy(endpoint)(method)("200");
const exampleKind = exampleNames[0];
if (exampleKind === undefined) {
throw new Error("could not get example names");
}
const preference = _req.headers.get("Prefer")
? parsePreferHeader(_req.headers.get("Prefer"))
: {
code: "200",
example: exampleKind,
};
if (preference.code === undefined) {
preference.code = "200";
}
if (preference.code === "200") {
if (typeof preference.example === "string") {
if (
openAPISpecTools.isValidExampleNameBy(endpoint)(method)(
preference.code
)(preference.example)
) {
return res(
ctx.json(
openAPISpecTools.getExampleBy(endpoint)(method)(
preference.code
)(preference.example)
)
);
}
return res(
ctx.json(
openAPISpecTools.getExampleBy(endpoint)(method)(
preference.code
)(exampleKind)
)
);
}
}
// 以降、エラーハンドリングなどを記述
});
});
})
.flat();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment