UNPKG

@nano-router/routes

Version:

Objects to setup routes

52 lines (47 loc) 1.26 kB
import { PathPattern } from '@nano-router/path'; class Route { name; external; #pattern; constructor(name, pattern, external = false) { if (name === "default") { throw new Error("default is a reserved route name"); } this.name = name; this.#pattern = new PathPattern(pattern); this.external = external; } match(path) { return this.#pattern.match(path); } stringify(params) { return this.#pattern.stringify(params); } } class ExternalRoute extends Route { constructor(name, pattern) { super(name, pattern, true); } } class Routes { #routes; constructor(...routes) { this.#routes = routes; } match(path) { for (let i = 0; i < this.#routes.length; i++) { const route = this.#routes[i]; if (route) { const match = route.match(path); if (match) { return { name: route.name, params: match }; } } } return { name: "default", params: {} }; } byName(name) { return this.#routes.find((route) => route.name === name) || null; } } export { ExternalRoute, Route, Routes };