AnP/Public/ecma/Models/RouteModel.ecma.js
2026-06-20 10:04:54 +02:00

82 lines
2.2 KiB
JavaScript

"use strict";
import {Check} from "../Utils/Checks.ecma.js";
import {Common} from "../Utils/Common.ecma.js";
import {RE} from "../Utils/Patterns.ecma.js";
/**
* @class RouteModel
* @constructor
* @param {!(string|RegExp)} route
* @param {!string} view
* @param {Array.<string>} [permissions = []]
* @returns {void}
* @access public
* @static
*/
export const RouteModel = (function(){
/**
* @constructs RouteModel
* @param {!(string|RegExp)} route
* @param {!string} view
* @param {Array.<string>} [permissions = []]
* @returns {void}
* @access private
* @static
*/
const RouteModel = function(route, view, permissions = []){
/** @type {RouteModel} */
const self = this;
/** @type {RegExp|null} */
this.route = null;
/** @type {Array.<string>} */
this.variables = [];
/** @type {string} */
this.view = view;
/** @type {Array.<strings>} */
this.permissions = permissions;
/**
* @returns {void}
* @access private
*/
const constructor = () => {
if(Check.is_string(route))
self.route = new RegExp("^" + Common.to_regular_expression(route.replace(RE.STRING_VARIABLES, (_, key) => {
self.variables.push(key);
return "#######";
})).replace(/#{7}/g, "([^\\/]+)") + "\\/?$", "i");
else if(Check.is_regular_expression(route))
(self.route = route).source.replace(/\([^\(\)]+\)/g, all => {
self.variables.push("" + self.variables.length);
return all;
});
};
/**
* @param {!string} url
* @returns {[!boolean, Object.<string, string>]}
* @access public
*/
this.check = url => {
/** @type {RegExpMatchArray} */
const matches = url.match(self.route);
return matches ? [true, self.variables.reduce((variables, key, i) => {
variables[key] = matches[i + 1];
return variables;
}, {})] : [false, {}];
}
constructor();
};
return RouteModel;
})();