Created
May 30, 2023 14:34
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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