Skip to content

Commit

Permalink
Add PrependBasePath test
Browse files Browse the repository at this point in the history
  • Loading branch information
zoontek committed Oct 18, 2022
1 parent 5dc11d5 commit b800ffd
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 10 deletions.
33 changes: 33 additions & 0 deletions __tests__/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
NonEmptySplit,
ParseRoute,
ParseRoutes,
PrependBasePath,
} from "../src/types";

// @ts-expect-error
Expand Down Expand Up @@ -114,3 +115,35 @@ test("GetAreaRoutes", () => {
}>(),
);
});

test("PrependBasePath", () => {
type Input = {
a: ParseRoute<"/">;
b: ParseRoute<"/foo/bar">;
c: ParseRoute<"/foo?:bar#:baz">;
};

expectType<PrependBasePath<"", Input>>(
toBe<{
a: { path: "/"; search: ""; hash: "" };
b: { path: "/foo/bar"; search: ""; hash: "" };
c: { path: "/foo"; search: ":bar"; hash: ":baz" };
}>(),
);

expectType<PrependBasePath<"/", Input>>(
toBe<{
a: { path: "/"; search: ""; hash: "" };
b: { path: "/foo/bar"; search: ""; hash: "" };
c: { path: "/foo"; search: ":bar"; hash: ":baz" };
}>(),
);

expectType<PrependBasePath<"/base", Input>>(
toBe<{
a: { path: "/base"; search: ""; hash: "" };
b: { path: "/base/foo/bar"; search: ""; hash: "" };
c: { path: "/base/foo"; search: ":bar"; hash: ":baz" };
}>(),
);
});
11 changes: 4 additions & 7 deletions src/createRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,21 @@ import {
ParsedRoute,
ParseRoute,
ParseRoutes,
PrependBaseRoute,
PrependBasePath,
Simplify,
} from "./types";

export const createRouter = <
Routes extends Record<string, string>,
BasePath extends string = "/",
BasePath extends string = "",
>(
routes: Readonly<Routes>,
options: {
basePath?: BasePath;
} = {},
) => {
type RoutesWithBasePath = PrependBaseRoute<
ParseRoute<BasePath>,
ParseRoutes<Routes>
>;

type CleanBasePath = ParseRoute<BasePath>["path"];
type RoutesWithBasePath = PrependBasePath<CleanBasePath, ParseRoutes<Routes>>;
type AreaRoutes = GetAreaRoutes<RoutesWithBasePath>;
type AreaRoutesParams = GetRoutesParams<AreaRoutes>;
type FiniteRoutes = Omit<RoutesWithBasePath, keyof AreaRoutes>;
Expand Down
6 changes: 3 additions & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,12 @@ export type ConcatRoutes<
"?"
>}${AddPrefixOnNonEmpty<Route["hash"], "#">}`;

export type PrependBaseRoute<
BaseRoute extends ParsedRoute,
export type PrependBasePath<
BasePath extends string,
Routes extends Record<string, ParsedRoute>,
> = {
[K in keyof Routes]: {
path: ConcatPaths<BaseRoute["path"], Routes[K]["path"]>;
path: ConcatPaths<BasePath, Routes[K]["path"]>;
search: Routes[K]["search"];
hash: Routes[K]["hash"];
};
Expand Down

0 comments on commit b800ffd

Please sign in to comment.