exstack
Version:
A utility library designed to simplify and enhance Express.js applications.
70 lines (68 loc) • 2.12 kB
JavaScript
const require_utils = require('./utils.cjs');
//#region src/router/param.ts
const tryDecodeURIComponent = (str) => require_utils.tryDecode(str, decodeURIComponent);
var Param = class {
/** Cache of decoded parameter values to avoid redundant decoding operations. */
#cache = /* @__PURE__ */ new Map();
constructor(req, matchResult) {
this.req = req;
this.matchResult = matchResult;
}
/**
* Retrieves the active route index for this request.
*/
#routeIndex = () => this.req.routeIndex || 0;
/**
* Retrieves the decoded value of a specific route parameter by key.
*
* @param {string} key - The name of the route parameter.
* @returns {string | undefined} The decoded parameter value, or `undefined` if not found.
*
* @example
* ```ts
* const userId = param.param('id');
* ```
*/
param = (key) => {
const routeIndex = this.#routeIndex();
const paramKey = this.matchResult[0][routeIndex][1][key];
const value = this.#getParamValue(paramKey);
return value ? this.#decode(value) : value;
};
/**
* Retrieves all decoded route parameters as a key-value record.
*
* @returns {Record<string, string>} An object mapping parameter names to decoded values.
*
* @example
* ```ts
* const allParams = param.params();
* // => { id: '123', name: 'John' }
* ```
*/
params = () => {
const routeIndex = this.#routeIndex();
const decoded = {};
const keys = Object.keys(this.matchResult[0][routeIndex][1]);
for (const key of keys) {
const value = this.#getParamValue(this.matchResult[0][routeIndex][1][key]);
if (value !== void 0) decoded[key] = this.#decode(value);
}
return decoded;
};
/**
* Resolves the parameter value from the match result.
*/
#getParamValue = (paramKey) => this.matchResult[1] ? this.matchResult[1][paramKey] : paramKey;
/**
* Decodes a URL-encoded parameter value and caches the result.
*/
#decode = (value) => {
if (this.#cache.has(value)) return this.#cache.get(value);
const decoded = value.includes("%") ? tryDecodeURIComponent(value) : value;
this.#cache.set(value, decoded);
return decoded;
};
};
//#endregion
exports.Param = Param;