minor refactoring in router, clarifying names and complicating parameter objects
[squeep-api-dingus] / lib / router / path-parameter.js
diff --git a/lib/router/path-parameter.js b/lib/router/path-parameter.js
new file mode 100644 (file)
index 0000000..585aaec
--- /dev/null
@@ -0,0 +1,49 @@
+'use strict';
+
+const kPathParameter = Symbol('kSqueepDingusRouterPathParameter');
+const parameters = new Map();
+/**
+ * De-duplicating factory of minimal-objects to track the named-parameter parts of path definitions.
+ *
+ * @property {String} parameter
+ */
+class PathParameter extends null {
+  constructor(parameter) {
+    if (!parameter || typeof(parameter) !== 'string') {
+      throw new RangeError('parameter must be string');
+    }
+    if (parameters.has(parameter)) {
+      return parameters.get(parameter);
+    }
+    const pathParameter = Object.create(PathParameter.prototype);
+    pathParameter[kPathParameter] = parameter; // eslint-disable-line security/detect-object-injection
+    parameters.set(parameter, pathParameter);
+    Object.freeze(pathParameter);
+    return pathParameter;
+  }
+
+  /**
+   * Return the parameter name.
+   */
+  get parameter() {
+    return this[kPathParameter];// eslint-disable-line security/detect-object-injection
+  }
+
+  /**
+   * @returns {String}
+   */
+  toString() {
+    return `{${this.constructor.name} ${this.parameter}}`; // eslint-disable-line security/detect-object-injection
+  }
+
+  /**
+   * Clear the de-duplication table, for tests.
+   */
+  static _flush() {
+    this.parameters.clear();
+  }
+}
+PathParameter.kPathParameter = kPathParameter;
+PathParameter.parameters = parameters;
+
+module.exports = PathParameter;
\ No newline at end of file