@quicore/resource-id
Version:
Deterministic and compact ID generation for API resources using pluggable hashing.
83 lines (75 loc) • 2.83 kB
JavaScript
import { GenerateHash } from '@quicore/hash';
/**
* Abstract class for generating deterministic IDs based on normalized input components.
* Intended for subclasses that define specific domain logic for ID structure.
*/
export class IDGenerator {
constructor(defaultIdLength = GenerateHash.DEFAULT_ID_LENGTH) {
/** @protected */
this.idLength = defaultIdLength;
/** @protected */
this.components = {};
}
/**
* Sets the desired output ID length.
* @param {number} length - Desired output length (minimum: MIN_ID_LENGTH).
* @returns {this} Returns the instance for method chaining.
* @throws {Error} If the length is below the minimum allowed.
*/
setIdLength(length) {
if (length < GenerateHash.MIN_ID_LENGTH) {
throw new Error(`ID length must be at least ${GenerateHash.MIN_ID_LENGTH} characters`);
}
this.idLength = length;
return this;
}
/**
* Sets a component used for ID generation.
* @param {string} key - The name of the component (e.g., 'resourceId').
* @param {*} value - The value to normalize and include in hashing.
* @returns {this} Returns the instance for method chaining.
*/
setComponent(key, value) {
this.components[key] = this.normalizeId(value);
return this;
}
/**
* Subclasses must override this method to define the component string used for hashing.
* @abstract
* @returns {string} A canonical string representation of components.
*/
createCanonicalString() {
throw new Error("Subclasses must implement createCanonicalString()");
}
/**
* Subclasses must override this method to validate required components.
* @abstract
* @throws {Error} If required components are missing.
*/
validateComponents() {
throw new Error("Subclasses must implement validateComponents()");
}
/**
* Generates a deterministic, compact ID using the hash function.
* @returns {string} The generated compact ID.
*/
generate() {
this.validateComponents();
const inputString = this.createCanonicalString();
return GenerateHash.compactHash(inputString, this.idLength);
}
/**
* Normalizes various input types (array, object, primitive) into a consistent string format.
* @param {*} id - The input value to normalize.
* @returns {string} A normalized string representation.
*/
normalizeId(id) {
if (Array.isArray(id)) {
return id.join('|');
}
if (typeof id === 'object' && id !== null) {
return Object.values(id).join('|');
}
return String(id);
}
}