UNPKG

domain-objects

Version:

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

51 lines 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getUniqueIdentifier = void 0; const error_fns_1 = require("@ehmpathy/error-fns"); const type_fns_1 = require("type-fns"); const assertDomainObjectIsSafeToManipulate_1 = require("../constraints/assertDomainObjectIsSafeToManipulate"); const DomainEntity_1 = require("../instantiation/DomainEntity"); const DomainEvent_1 = require("../instantiation/DomainEvent"); const DomainLiteral_1 = require("../instantiation/DomainLiteral"); const DomainObject_1 = require("../instantiation/DomainObject"); const DomainEntityUniqueKeysMustBeDefinedError_1 = require("./DomainEntityUniqueKeysMustBeDefinedError"); /** * Extracts an object that identifies the domain object via unique key, for DomainEntity, DomainEvent, or DomainLiteral. * * Uses the definition of a DomainEntity, DomainEvent, or DomainLiteral in order to extract the properties that uniquely define the domain object, generically. */ const getUniqueIdentifier = (obj) => { var _a, _b; // make sure its an instance of DomainObject if (!(obj instanceof DomainObject_1.DomainObject)) throw new Error('getUniqueIdentifier called on object that is not an instance of a DomainObject. Are you sure you instantiated the object? (Related: see `DomainObject.nested`)'); // make sure that its safe to manipulate (0, assertDomainObjectIsSafeToManipulate_1.assertDomainObjectIsSafeToManipulate)(obj); // handle DomainEntity if (obj instanceof DomainEntity_1.DomainEntity || obj instanceof DomainEvent_1.DomainEvent) { const className = obj.constructor.name; const uniqueKeys = obj.constructor.unique; if (!uniqueKeys) throw new DomainEntityUniqueKeysMustBeDefinedError_1.DomainEntityUniqueKeysMustBeDefinedError({ entityName: className, nameOfFunctionNeededFor: 'getUniqueIdentifier', }); return (0, type_fns_1.pick)(obj, uniqueKeys.flat()); } // handle DomainLiteral if (obj instanceof DomainLiteral_1.DomainLiteral) { const ignoreList = (_a = obj.constructor.metadata) !== null && _a !== void 0 ? _a : [ 'id', 'uuid', ]; // these are keys we should ignore, because literals are unique on their natural keys - not metadata keys (e.g., id or uuid) const uniqueKeys = Object.keys(obj).filter((key) => !ignoreList.includes(key)); // literals are unique on all keys, other than the metadata ones we ignore return (0, type_fns_1.pick)(obj, uniqueKeys); } // throw error we get here, this is unexpected throw new error_fns_1.UnexpectedCodePathError('unexpected domain object type for getUniqueIdentifier. expected DomainLiteral, DomainEntity, or DomainEvent', { dobjClass: (_b = obj === null || obj === void 0 ? void 0 : obj.constructor) === null || _b === void 0 ? void 0 : _b.name, dobj: obj, }); }; exports.getUniqueIdentifier = getUniqueIdentifier; //# sourceMappingURL=getUniqueIdentifier.js.map