@jimengio/router-code-generator
v0.3.0
Published
> Router controller code generated of [ruled-router](https://github.com/jimengio/ruled-router).
Downloads
150
Readme
Router code generator
Router controller code generated of ruled-router.
Live version: http://fe.jimu.io/router-code-generator
Usage
yarn add --dev @jimengio/router-code-generator
import { generateTree } from "@jimengio/router-code-generator";
generateTree(jsonRules);
Simplified demos
- Basic router controller generator
[{ "name": "a", "path": "a" }]
export let genRouter = {
a: {
name: "a",
raw: "a",
path: () => `/a`,
go: () => switchPath(`/a`),
},
};
- Router with parameter
[
{
"name": "a",
"path": "a/:code"
}
]
export let genRouter = {
a_: {
name: "a",
raw: "a/:code",
path: (code: string) => `/a/${code}`,
go: (code: string) => switchPath(`/a/${code}`),
},
};
- Router with query options
[
{
"name": "a",
"path": "a",
"queries": ["a", "b"]
}
]
export let genRouter = {
a: {
name: "a",
raw: "a",
path: (queries?: IGenQueryA) => `/a?${qsStringify(queries)}`,
go: (queries?: IGenQueryA) => switchPath(`/a?${qsStringify(queries)}`),
},
};
export interface IGenQueryA {
a?: string;
b?: string;
}
- Nested router
[
{
"name": "a",
"path": "a",
"next": [
{
"name": "b",
"path": "b"
}
]
}
]
export let genRouter = {
a: {
name: "a",
raw: "a",
path: () => `/a`,
go: () => switchPath(`/a`),
b: {
name: "b",
raw: "b",
path: () => `/a/b`,
go: () => switchPath(`/a/b`),
},
},
};
- Parsed router types(Experimental):
generateTree(jsonRules, { addTypes: true });
[
{
"path": "a",
"queries": ["a"],
"next": [
{
"path": "b",
"queries": ["a", "b"]
},
{
"path": "d"
}
]
}
]
export interface GenRouterTypeTree {
a: {
name: "a";
params: {};
query: { a: string };
next: GenRouterTypeTree["a"]["b"] | GenRouterTypeTree["a"]["d"];
b: {
name: "b";
params: {};
query: { a: string; b: string };
next: null;
};
d: {
name: "d";
params: {};
query: { a: string };
next: null;
};
};
}
qsStringify
Recommended implementation for query string:
import queryString from "query-string";
let qsStringify = (queries: { [k: string]: any }) => {
return queryString.stringify(queries, { arrayFormat: "bracket" });
};
Also the parser should use the same formatter bracket
.
License
MIT