UNPKG

domain-objects

Version:

A simple, convenient way to represent domain objects, leverage domain knowledge, and add runtime validation in your code base.

58 lines 2.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.refByUnique = void 0; const helpful_errors_1 = require("helpful-errors"); const hasDeclaredUniqueKey_1 = require("./hasDeclaredUniqueKey"); /** * creates a reference to a domain object by its unique key * * extracts only the unique key properties from a domain object instance * * note * - you may need to explicitly annotate the type for proper inference * - e.g., `const ref = refByUnique<typeof SeaTurtle>(turtle)` * - automatic resolution of the relationship between instance and class.static properties is not yet possible in TypeScript * - recursively extracts references from nested domain objects * - if a unique key property is itself a domain object, it will recursively call refByUnique on it * * @example * ```ts * const turtle = new SeaTurtle({ uuid: '1', seawaterSecurityNumber: '821', name: 'Crush' }); * const ref = refByUnique<typeof SeaTurtle>(turtle); * // ref = { seawaterSecurityNumber: '821' } * ``` * * @example * ```ts * // with nested domain objects * const turtle = new SeaTurtle({ seawaterSecurityNumber: '821', name: 'Crush' }); * const shell = new SeaTurtleShell({ turtle, algea: 'ALIL' }); * const ref = refByUnique<typeof SeaTurtleShell>(shell); * // ref = { turtle: { seawaterSecurityNumber: '821' } } * ``` */ const refByUnique = (instance) => { // get the domain object constructor const DomainObjectConstructor = instance.constructor; const uniqueKeys = DomainObjectConstructor?.unique; if (!uniqueKeys) throw new helpful_errors_1.UnexpectedCodePathError('can not create refByUnique on a dobj which does not declare its .unique keys', { dobj: DomainObjectConstructor?.name, uniqueKeys }); // extract only the unique key properties from the instance const ref = {}; for (const key of uniqueKeys) { const value = instance[key]; // if the value is a nested domain object, recursively extract its reference // (gate shared with buildKeyContract via hasDeclaredUniqueKey — one source of truth) if (value && typeof value === 'object' && (0, hasDeclaredUniqueKey_1.hasDeclaredUniqueKey)(value.constructor)) { ref[key] = (0, exports.refByUnique)(value); } else { ref[key] = value; } } return ref; }; exports.refByUnique = refByUnique; //# sourceMappingURL=refByUnique.js.map