Skip to content

Commit 064ae0d

Browse files
committed
feat(compileRouterToString): support serializing custom code with { toJSON }
1 parent 4e25f0b commit 064ae0d

File tree

2 files changed

+5
-4
lines changed

2 files changed

+5
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ findRoute("GET", "/path/foo/bar");
113113

114114
Compile the router instance into a compact runnable code.
115115

116-
**IMPORTANT:** Route data must be serializable to JSON (i.e., no functions or classes).
116+
**IMPORTANT:** Route data must be serializable to JSON (i.e., no functions or classes) or implement the `toJSON` method to render custom code.
117117

118118
**Example:**
119119

src/compiler.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export function compileRouter<T>(
3131
/**
3232
* Compile the router instance into a compact runnable code.
3333
*
34-
* **IMPORTANT:** Route data must be serializable to JSON (i.e., no functions or classes).
34+
* **IMPORTANT:** Route data must be serializable to JSON (i.e., no functions or classes) or implement the `toJSON` method to render custom code.
3535
*
3636
*
3737
* @example
@@ -95,9 +95,10 @@ function compileMethodMatch(
9595
if (data && data?.length > 0) {
9696
// Don't check for all method handler
9797
if (key !== "") str += `if(m==='${key}')`;
98+
const dataValue = data[0].data;
9899
let returnData = deps
99-
? `return{data:d${deps.push(data[0].data)}`
100-
: `return{data:${JSON.stringify(data[0].data)}`;
100+
? `return{data:d${deps.push(dataValue)}`
101+
: `return{data:${typeof dataValue?.toJSON === "function" ? dataValue.toJSON() : JSON.stringify(dataValue)}`;
101102

102103
// Add param properties
103104
const { paramsMap } = data[0];

0 commit comments

Comments
 (0)