UNPKG

@nano-router/routes

Version:

Objects to setup routes

56 lines (50 loc) 1.31 kB
'use strict'; var path = require('@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 path.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; } } exports.ExternalRoute = ExternalRoute; exports.Route = Route; exports.Routes = Routes;