minor refactoring in router, clarifying names and complicating parameter objects
[squeep-api-dingus] / lib / router / path-parameter.js
1 'use strict';
2
3 const kPathParameter = Symbol('kSqueepDingusRouterPathParameter');
4 const parameters = new Map();
5 /**
6 * De-duplicating factory of minimal-objects to track the named-parameter parts of path definitions.
7 *
8 * @property {String} parameter
9 */
10 class PathParameter extends null {
11 constructor(parameter) {
12 if (!parameter || typeof(parameter) !== 'string') {
13 throw new RangeError('parameter must be string');
14 }
15 if (parameters.has(parameter)) {
16 return parameters.get(parameter);
17 }
18 const pathParameter = Object.create(PathParameter.prototype);
19 pathParameter[kPathParameter] = parameter; // eslint-disable-line security/detect-object-injection
20 parameters.set(parameter, pathParameter);
21 Object.freeze(pathParameter);
22 return pathParameter;
23 }
24
25 /**
26 * Return the parameter name.
27 */
28 get parameter() {
29 return this[kPathParameter];// eslint-disable-line security/detect-object-injection
30 }
31
32 /**
33 * @returns {String}
34 */
35 toString() {
36 return `{${this.constructor.name} ${this.parameter}}`; // eslint-disable-line security/detect-object-injection
37 }
38
39 /**
40 * Clear the de-duplication table, for tests.
41 */
42 static _flush() {
43 this.parameters.clear();
44 }
45 }
46 PathParameter.kPathParameter = kPathParameter;
47 PathParameter.parameters = parameters;
48
49 module.exports = PathParameter;