UNPKG

@zenweb/router

Version:

Zenweb Router module

112 lines (111 loc) 2.88 kB
import { Middleware } from "@zenweb/core"; import { RouterMatch, RouterMethod, RouterOptions, RouterPath, RouterRegisterOption } from "./types"; export declare class RouterDuplicated extends Error { path: string; method: RouterMethod; constructor(path: string, method: RouterMethod); } export declare class Router { private option?; /** * 所有路由的中间件 */ private _middlewares?; /** * 子路由 */ private _routers?; /** * 静态路径 * /some/sub */ private _staticPaths?; /** * 通配符路径 * /some/* */ private _wildcardPaths?; /** * 参数化路径 * /some/:id/sub */ private _paramPath?; /** * 正则路径 * \^\/some\/.*$\i */ private _regexPaths?; /** * 数量统计 */ private _counts; constructor(option?: RouterOptions | undefined); private _registerStatic; private _registerRegex; private _registerWildcard; /** * 通配符匹配 */ private _matchByWildcard; private _registerParam; /** * 使用中间件 * - 匹配的路由将使用中间件 */ use(...middlewares: Middleware[]): this; /** * 添加子路由 * - 子路由继承父路由的中间件 */ add(...routers: Router[]): this; /** * 注册路由 * - 静态路径 * - 参数化路径 * - 路径中包含 `:` * - 通配符路径 (两端匹配优先) * - 两端匹配: /prefix/*\/suffix * - 前缀匹配: /prefix/* * - 后缀匹配: *\/auffix * - 正则表达式路径 * - /\\/some\\/(\d+)/i */ register(opt: RouterRegisterOption): this; all(path: RouterPath, ...middleware: Middleware[]): this; get(path: RouterPath, ...middleware: Middleware[]): this; post(path: RouterPath, ...middleware: Middleware[]): this; put(path: RouterPath, ...middleware: Middleware[]): this; patch(path: RouterPath, ...middleware: Middleware[]): this; delete(path: RouterPath, ...middleware: Middleware[]): this; /** * 静态匹配查找 */ private _matchByStatic; /** * 参数化路径匹配 */ private _matchByParam; /** * 正则匹配查找 */ private _matchByRegex; /** * 路径匹配查找 * - 匹配顺序: 静态 > 参数 > 通配符 > 正则 * - 方法顺序: 指定方法 > ALL */ match(path: string, method?: string): RouterMatch | undefined; /** * 匹配自身路由,忽略 prefix,不检查子路由 */ matchSelf(path: string, method: RouterMethod): RouterMatch | undefined; server(): Middleware; getCount(): { statics: number; params: number; wildcards: number; regexs: number; } & { subRouters: number; }; }