Skip to content

Commit

Permalink
feat: .dev prefix for dev only route
Browse files Browse the repository at this point in the history
  • Loading branch information
HigherOrderLogic committed Mar 17, 2024
1 parent fdf7e70 commit 9810d62
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,20 @@ type FileInfo = { path: string; fullPath: string };

const httpMethodRegex =
/\.(connect|delete|get|head|options|patch|post|put|trace)$/;
const devSuffixRegex = /\.dev$/;

export async function scanHandlers(nitro: Nitro) {
const middleware = await scanMiddleware(nitro);

const handlers = await Promise.all([
let handlers = await Promise.all([
scanServerRoutes(nitro, "api", "/api"),
scanServerRoutes(nitro, "routes", "/"),
]).then((r) => r.flat());

if (!nitro.options.dev) {
handlers = handlers.filter((h) => !h.devOnly);
}

nitro.scannedHandlers = [
...middleware,
...handlers.filter((h, index, array) => {
Expand Down Expand Up @@ -55,6 +60,12 @@ export async function scanServerRoutes(
.replace(/\[(\w+)]/g, ":$1");
route = withLeadingSlash(withoutTrailingSlash(withBase(route, prefix)));

let devOnly = false;
if (devSuffixRegex.test(route)) {
devOnly = true;
route = route.slice(0, Math.max(0, route.length - 4));
}

let method;
const methodMatch = route.match(httpMethodRegex);
if (methodMatch) {
Expand All @@ -70,6 +81,7 @@ export async function scanServerRoutes(
middleware: false,
route,
method,
devOnly,
};
});
}
Expand Down
4 changes: 4 additions & 0 deletions test/fixture/routes/dev-route-only.dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const sharedAppConfig = useAppConfig();
const sharedRuntimeConfig = useRuntimeConfig();

export default eventHandler(() => "You should only see this in dev mode.");
5 changes: 5 additions & 0 deletions test/presets/nitro-dev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ describe.skipIf(isCI)("nitro:preset:nitro-dev", async () => {
const { status } = await callHandler({ url: "/proxy/example" });
expect(status).toBe(200);
});

it("load dev only route", async () => {
const { status } = await callHandler({ url: "/dev-route-only" });
expect(status).toBe(200);
});
}
);
});

0 comments on commit 9810d62

Please sign in to comment.