Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix valid route detection #42

Merged
merged 3 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/next/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@stl-api/next",
"version": "0.1.4",
"version": "0.1.5",
"license": "ISC",
"description": "next.js plugin for stainless api",
"author": "[email protected]",
Expand Down
21 changes: 15 additions & 6 deletions packages/next/src/nextPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { TrieRouter } from "hono/router/trie-router";
import { endpointToHono } from "./endpointToHono";
import { NextRequest, NextResponse } from "next/server";
import { Result } from "hono/router";

declare module "stainless" {
interface StlContext<EC extends AnyBaseEndpoint> {
Expand Down Expand Up @@ -107,9 +108,9 @@ function makeRouter(
const { pathname, search } = new URL(url);
const match = routeMatcher.match(method, pathname);

if (!match) {
const enabledMethods = methods.filter(
(method) => routeMatcher.match(method, pathname) != null
if (!isValidRouteMatch(match)) {
const enabledMethods = methods.filter((method) =>
isValidRouteMatch(routeMatcher.match(method, pathname))
);
if (enabledMethods.length) {
return NextResponse.json(
Expand Down Expand Up @@ -187,9 +188,9 @@ function makeRouter(
const { pathname } = new URL(`http://localhost${url}`);
const match = routeMatcher.match(method, pathname);

if (!match) {
const enabledMethods = methods.filter(
(method) => routeMatcher.match(method, pathname) != null
if (!isValidRouteMatch(match)) {
const enabledMethods = methods.filter((method) =>
isValidRouteMatch(routeMatcher.match(method, pathname))
);
if (enabledMethods.length) {
res.status(405).json({
Expand Down Expand Up @@ -248,6 +249,14 @@ function makeRouter(
return { appHandler, pagesHandler };
}

const isValidRouteMatch = (m: Result<AnyEndpoint>) => {
if (!m) return false;

if (m[0].length === 0) return false;

return true;
};

export const stlNextPageRoute = <Endpoints extends AnyEndpoint[]>(
...endpoints: Endpoints
) => makeRouter(endpoints).pagesHandler;
Expand Down
Loading