UNPKG

goodrouter

Version:
91 lines (90 loc) 2.65 kB
import { RouterJson } from "./json.js"; import { defaultRouterOptions, RouterOptions } from "./router-options.js"; export declare enum RouterMode { Client = 2, Server = 4, Bidirectional = 6 } /** * @description * This is the actual router that contains all routes and does the actual routing * * @example * ```typescript * const router = new Router<string>(); * * router.insertRoute("all-products", "/product/all"); * router.insertRoute("product-detail", "/product/{id}"); * * // And now we can parse routes! * * { * const [routeKey, routeParameters] = router.parseRoute("/not-found"); * assert.equal(routeKey, null); * assert.deepEqual(routeParameters, {}); * } * * { * const [routeKey, routeParameters] = router.parseRoute("/product/all"); * assert.equal(routeKey, "all-products"); * assert.deepEqual(routeParameters, {}); * } * * { * const [routeKey, routeParameters] = router.parseRoute("/product/1"); * assert.equal(routeKey, "product-detail"); * assert.deepEqual(routeParameters, { id: "1" }); * } * * // And we can stringify routes * * { * const path = router.stringifyRoute( * "all-products", * }); * assert.equal(path, "/product/all"); * } * * { * const path = router.stringifyRoute( * "product-detail", * { id: "2" }, * ); * assert.equal(path, "/product/2"); * } * ``` */ export declare class Router<K extends string | number> { private mode; constructor(options?: RouterOptions, mode?: RouterMode); protected options: RouterOptions & typeof defaultRouterOptions; private rootNode; private templatePairs; /** * @description * Adds a new route * * @param routeKey name of the route * @param routeTemplate template for the route, als defines parameters */ insertRoute(routeKey: K, routeTemplate: string): this; /** * @description * Match the path against a known routes and parse the parameters in it * * @param path path to match * @returns tuple with the route name or null if no route found. Then the parameters */ parseRoute(path: string): [K | null, Record<string, string>]; /** * @description * Convert a route to a path string. * * @param routeKey route to stringify * @param routeParameters parameters to include in the path * @returns string representing the route or null if the route is not found by name */ stringifyRoute(routeKey: K, routeParameters?: Record<string, string>): string | null; saveToJson(mode?: RouterMode): RouterJson<K>; loadFromJson(json: RouterJson<K>): this; }