UNPKG

domain-objects

Version:

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

42 lines 2.68 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPrimaryIdentifier = void 0; const helpful_errors_1 = require("helpful-errors"); const type_fns_1 = require("type-fns"); const assertDomainObjectIsSafeToManipulate_1 = require("../constraints/assertDomainObjectIsSafeToManipulate"); const isOfDomainEntity_1 = require("../instantiation/inherit/isOfDomainEntity"); const isOfDomainEvent_1 = require("../instantiation/inherit/isOfDomainEvent"); const isOfDomainLiteral_1 = require("../instantiation/inherit/isOfDomainLiteral"); const isOfDomainObject_1 = require("../instantiation/inherit/isOfDomainObject"); const DomainEntityPrimaryKeysMustBeDefinedError_1 = require("./DomainEntityPrimaryKeysMustBeDefinedError"); /** * Extracts an object that identifies the domain object via primary key, for DomainEntity, DomainEvent, or DomainLiteral. * * Uses the definition of a DomainEntity, DomainEvent, or DomainLiteral in order to extract the primary key of the dobj, generically. */ const getPrimaryIdentifier = (obj) => { // make sure its an instance of DomainObject if (!(0, isOfDomainObject_1.isOfDomainObject)(obj)) throw new helpful_errors_1.BadRequestError('getUniqueIdentifier called on object that is not an instance of a DomainObject. Are you sure you instantiated the object? (Related: see `DomainObject.nested`)', { obj }); // make sure that its safe to manipulate (0, assertDomainObjectIsSafeToManipulate_1.assertDomainObjectIsSafeToManipulate)(obj); // handle DomainEntity, DomainEvent, and DomainLiteral if ((0, isOfDomainEntity_1.isOfDomainEntity)(obj) || (0, isOfDomainEvent_1.isOfDomainEvent)(obj) || (0, isOfDomainLiteral_1.isOfDomainLiteral)(obj)) { const className = obj.constructor.name; const primaryKeys = obj.constructor.primary; if (!primaryKeys) throw new DomainEntityPrimaryKeysMustBeDefinedError_1.DomainEntityPrimaryKeysMustBeDefinedError({ entityName: className, nameOfFunctionNeededFor: 'getPrimaryIdentifier', }); const primary = (0, type_fns_1.pick)(obj, primaryKeys.flat()); return Object.keys(primary).length ? primary : undefined; // if no primary found in instance -> undefined } // throw error we get here, this is unexpected throw new helpful_errors_1.UnexpectedCodePathError('unexpected domain object type for getUniqueIdentifier. expected DomainLiteral, DomainEntity, or DomainEvent', { dobjClass: obj?.constructor?.name, dobj: obj, }); }; exports.getPrimaryIdentifier = getPrimaryIdentifier; //# sourceMappingURL=getPrimaryIdentifier.js.map