Skip to content

Commit

Permalink
implements custom parameter placeholders
Browse files Browse the repository at this point in the history
  • Loading branch information
kruschid committed Sep 10, 2024
1 parent e6877c7 commit ed6cdc7
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ export const renderTemplate = ({
.map((pathSegment) =>
typeof pathSegment === "string"
? pathSegment
: `:${pathSegment.name}${pathSegment.kind === "optional" ? "?" : ""}`
: pathSegment.options?.template ??
`:${pathSegment.name}${pathSegment.kind === "optional" ? "?" : ""}`
)
.join("/");

Expand Down
15 changes: 12 additions & 3 deletions src/params.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import type { Param, Parser } from "./types";
import type { Param, ParamOptions, Parser } from "./types";

export const param = <T>(parser: Parser<T>) => {
const fn = <N extends string>(name: N): Param<N, T, "required"> => ({
const fn = <N extends string>(
name: N,
options?: ParamOptions
): Param<N, T, "required"> => ({
name,
parser,
kind: "required",
options,
});
fn.optional = <N extends string>(name: N): Param<N, T, "optional"> => ({

fn.optional = <N extends string>(
name: N,
options?: ParamOptions
): Param<N, T, "optional"> => ({
name,
parser,
kind: "optional",
options,
});
return fn;
};
Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ export type ParamKind = "optional" | "required";

export type AnyParam = Param<string, any, any>;

export interface ParamOptions {
template?: string;
}

export type Param<N = string, T = any, K extends ParamKind = "required"> = {
name: N;
options?: ParamOptions;
kind: K;
parser: Parser<T>;
};
Expand Down
17 changes: 17 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ test("templates with default renderer", (t) => {
t.equal(routes.blog._.category._wildcard.$template(), "category/:cid/**");
t.equal(routes.blog._.category.date.$template(), "category/:cid/:date");
t.equal(routes.blog.category._.date.$template(), ":date");

t.end();
});

test("custom templates with default renderer ", (t) => {
const routes = createRoutes({
customTemplate: {
template: "segment/:param/segment",
},
customParamTemplate: {
path: ["segment", str("title", { template: ":title.(mp4|mov)" })],
},
});

t.equal(routes.customTemplate.$template(), "/segment/:param/segment");
t.equal(routes.customParamTemplate.$template(), "/segment/:title.(mp4|mov)");

t.end();
});

Expand Down

0 comments on commit ed6cdc7

Please sign in to comment.