UNPKG

@ima/core

Version:

IMA.js framework for isomorphic javascript application

56 lines (55 loc) 2.33 kB
import { AbstractRoute } from './AbstractRoute'; import { GenericError } from '../error/GenericError'; /** * Utility for representing and manipulating a single dynamic route in the * router's configuration. Dynamic route is defined by regExp used for route * matching and overrides for toPath and extractParameters functions to generate * and put together valid path. * * @extends AbstractRoute */ export class DynamicRoute extends AbstractRoute { /** * Initializes the route. * * @param pathExpression Path expression used in route matching, * to generate valid path with provided params and parsing params from current path. */ constructor(name, pathExpression, controller, view, options){ super(name, pathExpression, controller, view, options); if (!pathExpression || typeof pathExpression !== 'object') { throw new GenericError(`The pathExpression must be object, '${typeof pathExpression}' was given.`); } this._pathExpression = pathExpression; const { matcher, toPath, extractParameters } = this._pathExpression; if (!matcher || !(matcher instanceof RegExp)) { throw new GenericError(`The pathExpression.matcher must be a RegExp.`, { matcher }); } if (!toPath || typeof toPath !== 'function') { throw new GenericError(`The pathExpression.toPath is not a function, '${typeof toPath}' was given.`); } if (!extractParameters || typeof extractParameters !== 'function') { throw new GenericError(`The pathExpression.extractParameters is not a function, '${typeof extractParameters}' was given.`); } } /** * @inheritDoc */ toPath(params = {}) { return this.getTrimmedPath(this._pathExpression.toPath(params)); } /** * @inheritDoc */ matches(path) { return this._pathExpression.matcher.test(this.getTrimmedPath(path)); } /** * @inheritDoc */ extractParameters(path, baseUrl) { const parsedUrl = new URL(`${baseUrl}${path}`); return this._pathExpression.extractParameters(this.getTrimmedPath(parsedUrl.pathname), { path, query: Object.fromEntries(parsedUrl.searchParams) }); } } //# sourceMappingURL=DynamicRoute.js.map