Skip to content

Instantly share code, notes, and snippets.

@SevenOutman
Created May 30, 2023 14:34
Show Gist options
  • Save SevenOutman/3acfd104910660862c4bfbedd5e0f4ec to your computer and use it in GitHub Desktop.
Save SevenOutman/3acfd104910660862c4bfbedd5e0f4ec to your computer and use it in GitHub Desktop.
This gist demonstrates how you can manage Mock Service Worker handlers in Next.js API Routes style in your Vite project
import { rest } from "msw";
// https://vitejs.dev/guide/features.html#glob-import
const imports = import.meta.glob("./api/**/*.ts", { eager: true });
export const handlers = Object.entries(imports).reduce(
(allHandlers, [path, handlers]) => {
// map "./path/[to]/handlers.js" -> "/api/path/:to/handlers"
const apiPath =
"/" +
path
// trim "./" at start
.replace(/^\.\//, "")
// trim ".js" at end
.replace(/\.[^/.]+$/, "")
// replace "[param]" with ":param"
.replace(/\[([^/]*)\]/g, ":$1");
Object.getOwnPropertyNames(handlers).forEach((verb) => {
const handler = handlers[verb];
const method = verb.toLowerCase();
// for every method in handlers, register an msw handler
if (method in rest) {
allHandlers.push(rest[method as keyof typeof rest](apiPath, handler));
}
});
return allHandlers;
},
[]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment